VID_Init now takes an int bpp parameter
[divverent/darkplaces.git] / vid_glx.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 //#include <termios.h>
21 //#include <sys/ioctl.h>
22 //#include <sys/stat.h>
23 //#include <sys/vt.h>
24 //#include <stdarg.h>
25 //#include <stdio.h>
26 #include <signal.h>
27
28 #include <dlfcn.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/Xutil.h>
32 #include <GL/glx.h>
33
34 #include <X11/keysym.h>
35 #include <X11/cursorfont.h>
36
37 #include <X11/extensions/XShm.h>
38 #include <X11/extensions/xf86dga.h>
39 #include <X11/extensions/xf86vmode.h>
40
41 #include "quakedef.h"
42
43 int cl_available = true;
44
45 //GLX prototypes
46 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
47 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
48 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
49 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
50 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
51 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
52
53 //GLX_ARB_get_proc_address
54 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
55
56 static gl_extensionfunctionlist_t getprocaddressfuncs[] =
57 {
58         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
59         {NULL, NULL}
60 };
61
62 //GLX_SGI_video_sync
63 GLint (GLAPIENTRY *qglXGetVideoSyncSGI)(GLuint *count);
64 GLint (GLAPIENTRY *qglXWaitVideoSyncSGI)(int divisor, int remainder, unsigned int *count);
65
66 static gl_extensionfunctionlist_t videosyncfuncs[] =
67 {
68         {"glXGetVideoSyncSGI", (void **) &qglXGetVideoSyncSGI},
69         {"glXWaitVideoSyncSGI", (void **) &qglXWaitVideoSyncSGI},
70         {NULL, NULL}
71 };
72
73 static Display *vidx11_display = NULL;
74 static int scrnum;
75 static Window win;
76 static GLXContext ctx = NULL;
77
78 Atom wm_delete_window_atom;
79
80 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
81 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
82                     PointerMotionMask | ButtonMotionMask )
83 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | StructureNotifyMask )
84
85
86 viddef_t        vid;                            // global video state
87
88 static qboolean         mouse_avail = true;
89 static qboolean         mouse_active = false, usingmouse = false;
90 static float    mouse_x, mouse_y;
91 static int p_mouse_x, p_mouse_y;
92
93 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
94 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
95
96 qboolean vidmode_ext = false;
97
98 static int win_x, win_y;
99
100 static int scr_width, scr_height;
101
102 static XF86VidModeModeInfo **vidmodes;
103 static int num_vidmodes;
104 static qboolean vidmode_active = false;
105
106 static Visual *vidx11_visual;
107 static Colormap vidx11_colormap;
108
109 /*-----------------------------------------------------------------------*/
110
111 static int
112 XLateKey(XKeyEvent *ev)
113 {
114         int key = 0;
115         KeySym keysym;
116
117         keysym = XLookupKeysym(ev, 0);
118
119         switch(keysym)
120         {
121                 case XK_KP_Page_Up:     key = KP_PGUP; break;
122                 case XK_Page_Up:        key = K_PGUP; break;
123
124                 case XK_KP_Page_Down:   key = KP_PGDN; break;
125                 case XK_Page_Down:      key = K_PGDN; break;
126
127                 case XK_KP_Home:        key = KP_HOME; break;
128                 case XK_Home:           key = K_HOME; break;
129
130                 case XK_KP_End:         key = KP_END; break;
131                 case XK_End:            key = K_END; break;
132
133                 case XK_KP_Left:        key = KP_LEFTARROW; break;
134                 case XK_Left:           key = K_LEFTARROW; break;
135
136                 case XK_KP_Right:       key = KP_RIGHTARROW; break;
137                 case XK_Right:          key = K_RIGHTARROW; break;
138
139                 case XK_KP_Down:        key = KP_DOWNARROW; break;
140                 case XK_Down:           key = K_DOWNARROW; break;
141
142                 case XK_KP_Up:          key = KP_UPARROW; break;
143                 case XK_Up:                     key = K_UPARROW; break;
144
145                 case XK_Escape:         key = K_ESCAPE; break;
146
147                 case XK_KP_Enter:       key = KP_ENTER; break;
148                 case XK_Return:         key = K_ENTER; break;
149
150                 case XK_Tab:            key = K_TAB; break;
151
152                 case XK_F1:                     key = K_F1; break;
153                 case XK_F2:                     key = K_F2; break;
154                 case XK_F3:                     key = K_F3; break;
155                 case XK_F4:                     key = K_F4; break;
156                 case XK_F5:                     key = K_F5; break;
157                 case XK_F6:                     key = K_F6; break;
158                 case XK_F7:                     key = K_F7; break;
159                 case XK_F8:                     key = K_F8; break;
160                 case XK_F9:                     key = K_F9; break;
161                 case XK_F10:            key = K_F10; break;
162                 case XK_F11:            key = K_F11; break;
163                 case XK_F12:            key = K_F12; break;
164
165                 case XK_BackSpace:      key = K_BACKSPACE; break;
166
167                 case XK_KP_Delete:      key = KP_DEL; break;
168                 case XK_Delete:         key = K_DEL; break;
169
170                 case XK_Pause:          key = K_PAUSE; break;
171
172                 case XK_Shift_L:
173                 case XK_Shift_R:        key = K_SHIFT; break;
174
175                 case XK_Execute:
176                 case XK_Control_L:
177                 case XK_Control_R:      key = K_CTRL; break;
178
179                 case XK_Mode_switch:
180                 case XK_Alt_L:
181                 case XK_Meta_L:
182                 case XK_Alt_R:
183                 case XK_Meta_R:         key = K_ALT; break;
184
185                 case XK_Caps_Lock:      key = K_CAPSLOCK; break;
186                 case XK_KP_Begin:       key = KP_5; break;
187
188                 case XK_Insert:         key = K_INS; break;
189                 case XK_KP_Insert:      key = KP_INS; break;
190
191                 case XK_KP_Multiply:    key = KP_MULTIPLY; break;
192                 case XK_KP_Add:         key = KP_PLUS; break;
193                 case XK_KP_Subtract:    key = KP_MINUS; break;
194                 case XK_KP_Divide:      key = KP_DIVIDE; break;
195
196                 /* For Sun keyboards */
197                 case XK_F27:            key = K_HOME; break;
198                 case XK_F29:            key = K_PGUP; break;
199                 case XK_F33:            key = K_END; break;
200                 case XK_F35:            key = K_PGDN; break;
201
202                 default:
203                         if (keysym < 128)
204                         {
205                                 /* ASCII keys */
206                                 key = keysym;
207                                 if ((key >= 'A') && (key <= 'Z'))
208                                         key = key + ('a' - 'A');
209                         }
210                         break;
211         }
212
213         return key;
214 }
215
216 static Cursor CreateNullCursor(Display *display, Window root)
217 {
218         Pixmap cursormask;
219         XGCValues xgc;
220         GC gc;
221         XColor dummycolour;
222         Cursor cursor;
223
224         cursormask = XCreatePixmap(display, root, 1, 1, 1);
225         xgc.function = GXclear;
226         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
227         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
228         dummycolour.pixel = 0;
229         dummycolour.red = 0;
230         dummycolour.flags = 04;
231         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
232         XFreePixmap(display,cursormask);
233         XFreeGC(display,gc);
234         return cursor;
235 }
236
237 static void install_grabs(void)
238 {
239         XWindowAttributes attribs_1;
240         XSetWindowAttributes attribs_2;
241
242         XGetWindowAttributes(vidx11_display, win, &attribs_1);
243         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
244         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
245
246 // inviso cursor
247         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
248
249         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
250
251         if (vid_dga.integer)
252         {
253                 int MajorVersion, MinorVersion;
254
255                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
256                 {
257                         // unable to query, probalby not supported
258                         Con_Printf( "Failed to detect XF86DGA Mouse\n" );
259                         vid_dga.integer = 0;
260                 }
261                 else
262                 {
263                         vid_dga.integer = 1;
264                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
265                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
266                 }
267         }
268         else
269                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
270
271         XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
272
273         mouse_active = true;
274         mouse_x = mouse_y = 0;
275 }
276
277 static void uninstall_grabs(void)
278 {
279         if (!vidx11_display || !win)
280                 return;
281
282         if (vid_dga.integer == 1)
283                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
284
285         XUngrabPointer(vidx11_display, CurrentTime);
286         XUngrabKeyboard(vidx11_display, CurrentTime);
287
288 // inviso cursor
289         XUndefineCursor(vidx11_display, win);
290
291         mouse_active = false;
292 }
293
294 static void HandleEvents(void)
295 {
296         XEvent event;
297         qboolean dowarp = false;
298
299         if (!vidx11_display)
300                 return;
301
302         while (XPending(vidx11_display))
303         {
304                 XNextEvent(vidx11_display, &event);
305
306                 switch (event.type)
307                 {
308                 case KeyPress:
309                         // key pressed
310                         Key_Event(XLateKey(&event.xkey), true);
311                         break;
312
313                 case KeyRelease:
314                         // key released
315                         Key_Event(XLateKey(&event.xkey), false);
316                         break;
317
318                 case MotionNotify:
319                         // mouse moved
320                         if (usingmouse)
321                         {
322                                 if (vid_dga.integer == 1)
323                                 {
324                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
325                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
326                                 }
327                                 else
328                                 {
329
330                                         if (!event.xmotion.send_event)
331                                         {
332                                                 mouse_x += event.xmotion.x - p_mouse_x;
333                                                 mouse_y += event.xmotion.y - p_mouse_y;
334                                                 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
335                                                         dowarp = true;
336                                         }
337                                         p_mouse_x = event.xmotion.x;
338                                         p_mouse_y = event.xmotion.y;
339                                 }
340                         }
341                         else
342                                 ui_mouseupdate(event.xmotion.x, event.xmotion.y);
343                         break;
344
345                 case ButtonPress:
346                         // mouse button pressed
347                         switch(event.xbutton.button)
348                         {
349                         case 1:
350                                 Key_Event(K_MOUSE1, true);
351                                 break;
352                         case 2:
353                                 Key_Event(K_MOUSE3, true);
354                                 break;
355                         case 3:
356                                 Key_Event(K_MOUSE2, true);
357                                 break;
358                         case 4:
359                                 Key_Event(K_MWHEELUP, true);
360                                 break;
361                         case 5:
362                                 Key_Event(K_MWHEELDOWN, true);
363                                 break;
364                 default:
365                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-5 expected\n", event.xbutton.button);
366                                 break;
367                         }
368                         break;
369
370                 case ButtonRelease:
371                         // mouse button released
372                         switch(event.xbutton.button)
373                         {
374                         case 1:
375                                 Key_Event(K_MOUSE1, false);
376                                 break;
377                         case 2:
378                                 Key_Event(K_MOUSE3, false);
379                                 break;
380                         case 3:
381                                 Key_Event(K_MOUSE2, false);
382                                 break;
383                         case 4:
384                                 Key_Event(K_MWHEELUP, false);
385                                 break;
386                         case 5:
387                                 Key_Event(K_MWHEELDOWN, false);
388                                 break;
389                 default:
390                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-5 expected\n", event.xbutton.button);
391                                 break;
392                         }
393                         break;
394
395                 case CreateNotify:
396                         // window created
397                         win_x = event.xcreatewindow.x;
398                         win_y = event.xcreatewindow.y;
399                         break;
400
401                 case ConfigureNotify:
402                         // window changed size/location
403                         win_x = event.xconfigure.x;
404                         win_y = event.xconfigure.y;
405                         break;
406                 case DestroyNotify:
407                         // window has been destroyed
408                         Sys_Quit();
409                         break;
410                 case ClientMessage:
411                         // window manager messages
412                         if ((event.xclient.format == 32) && (event.xclient.data.l[0] == wm_delete_window_atom))
413                                 Sys_Quit();
414                         break;
415                 case MapNotify:
416                         // window restored
417                         vid_hidden = false;
418                         break;
419                 case UnmapNotify:
420                         // window iconified/rolledup/whatever
421                         vid_hidden = true;
422                         break;
423                 case FocusIn:
424                         // window is now the input focus
425                         break;
426                 case FocusOut:
427                         // window is no longer the input focus
428                         break;
429                 case EnterNotify:
430                         // mouse entered window
431                         break;
432                 case LeaveNotify:
433                         // mouse left window
434                         break;
435                 }
436         }
437
438         if (dowarp)
439         {
440                 /* move the mouse to the window center again */
441                 p_mouse_x = scr_width / 2;
442                 p_mouse_y = scr_height / 2;
443                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
444         }
445
446 }
447
448 static void IN_DeactivateMouse( void )
449 {
450         if (!mouse_avail || !vidx11_display || !win)
451                 return;
452
453         if (mouse_active)
454         {
455                 uninstall_grabs();
456                 mouse_active = false;
457         }
458 }
459
460 static void IN_ActivateMouse( void )
461 {
462         if (!mouse_avail || !vidx11_display || !win)
463                 return;
464
465         if (!mouse_active)
466         {
467                 mouse_x = mouse_y = 0; // don't spazz
468                 install_grabs();
469                 mouse_active = true;
470         }
471 }
472
473
474 void VID_Shutdown(void)
475 {
476         if (!ctx || !vidx11_display)
477                 return;
478
479         if (vidx11_display)
480         {
481                 uninstall_grabs();
482
483                 if (vidmode_active)
484                         XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[0]);
485                 if (win)
486                         XDestroyWindow(vidx11_display, win);
487                 XCloseDisplay(vidx11_display);
488         }
489         vidmode_active = false;
490         vidx11_display = NULL;
491         win = 0;
492         ctx = NULL;
493
494         GL_CloseLibrary();
495 }
496
497 void signal_handler(int sig)
498 {
499         printf("Received signal %d, exiting...\n", sig);
500         Sys_Quit();
501         exit(0);
502 }
503
504 void InitSig(void)
505 {
506         signal(SIGHUP, signal_handler);
507         signal(SIGINT, signal_handler);
508         signal(SIGQUIT, signal_handler);
509         signal(SIGILL, signal_handler);
510         signal(SIGTRAP, signal_handler);
511         signal(SIGIOT, signal_handler);
512         signal(SIGBUS, signal_handler);
513         signal(SIGFPE, signal_handler);
514         signal(SIGSEGV, signal_handler);
515         signal(SIGTERM, signal_handler);
516 }
517
518 /*
519 =================
520 VID_GetWindowSize
521 =================
522 */
523 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
524 {
525         *x = *y = 0;
526         *width = scr_width;
527         *height = scr_height;
528 }
529
530 void VID_Finish (void)
531 {
532         int usemouse;
533         if (r_render.integer)
534         {
535                 qglFinish();
536                 qglXSwapBuffers(vidx11_display, win);
537         }
538
539 // handle the mouse state when windowed if that's changed
540         usemouse = false;
541         if (vid_mouse.integer && !key_consoleactive)
542                 usemouse = true;
543         if (vidmode_active)
544                 usemouse = true;
545         if (usemouse)
546         {
547                 if (!usingmouse)
548                 {
549                         usingmouse = true;
550                         IN_ActivateMouse ();
551                 }
552         }
553         else
554         {
555                 if (usingmouse)
556                 {
557                         usingmouse = false;
558                         IN_DeactivateMouse ();
559                 }
560         }
561 }
562
563 // LordHavoc: ported from SDL 1.2.2, this was far more difficult to port from
564 // SDL than to simply use the XFree gamma ramp extension, but that affects the
565 // whole screen even when the game window is inactive, this only affects the
566 // screen while the window is active, very desirable behavior :)
567 int VID_SetGamma(float prescale, float gamma, float scale, float base)
568 {
569 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
570 #if 1
571         return FALSE;
572 #else
573         int i, ncolors, c;
574         unsigned int Rmask, Gmask, Bmask, Rloss, Gloss, Bloss, Rshift, Gshift, Bshift, mask;
575         XColor xcmap[256];
576         unsigned short ramp[256];
577
578         if (COM_CheckParm("-nogamma"))
579                 return FALSE;
580
581         if (vidx11_visual->class != DirectColor)
582         {
583                 Con_Printf("X11 Visual class is %d, can only do gamma on %d\n", vidx11_visual->class, DirectColor);
584                 return FALSE;
585         }
586
587         Rmask = vidx11_visual->red_mask;
588         Gmask = vidx11_visual->green_mask;
589         Bmask = vidx11_visual->blue_mask;
590
591         Rshift = 0;
592         Rloss = 8;
593         if ((mask = Rmask))
594         {
595                 for (;!(mask & 1);mask >>= 1)
596                         ++Rshift;
597                 for (;(mask & 1);mask >>= 1)
598                         --Rloss;
599         }
600         Gshift = 0;
601         Gloss = 8;
602         if ((mask = Gmask))
603         {
604                 for (;!(mask & 1);mask >>= 1)
605                         ++Gshift;
606                 for (;(mask & 1);mask >>= 1)
607                         --Gloss;
608         }
609         Bshift = 0;
610         Bloss = 8;
611         if ((mask = Bmask))
612         {
613                 for (;!(mask & 1);mask >>= 1)
614                         ++Bshift;
615                 for (;(mask & 1);mask >>= 1)
616                         --Bloss;
617         }
618
619         BuildGammaTable16(prescale, gamma, scale, base, ramp);
620
621         // convert gamma ramp to palette (yes this seems odd)
622         ncolors = vidx11_visual->map_entries;
623         for (i = 0;i < ncolors;i++)
624         {
625                 c = (256 * i / ncolors);
626                 xcmap[i].pixel = ((c >> Rloss) << Rshift) | ((c >> Gloss) << Gshift) | ((c >> Bloss) << Bshift);
627                 xcmap[i].red   = ramp[c];
628                 xcmap[i].green = ramp[c];
629                 xcmap[i].blue  = ramp[c];
630                 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
631         }
632         XStoreColors(vidx11_display, vidx11_colormap, xcmap, ncolors);
633         XSync(vidx11_display, false);
634         // FIXME: should this check for BadAccess/BadColor/BadValue errors produced by XStoreColors before setting this true?
635         return TRUE;
636 #endif
637 }
638
639 void VID_Init(int fullscreen, int width, int height, int bpp)
640 {
641         int i;
642 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
643 #if 0
644         int gammaattrib[] =
645         {
646                 GLX_RGBA,
647                 GLX_RED_SIZE, 1,
648                 GLX_GREEN_SIZE, 1,
649                 GLX_BLUE_SIZE, 1,
650                 GLX_DOUBLEBUFFER,
651                 GLX_DEPTH_SIZE, 1,
652                 GLX_X_VISUAL_TYPE, GLX_DIRECT_COLOR,
653                 None
654         };
655 #endif
656         int nogammaattrib[] =
657         {
658                 GLX_RGBA,
659                 GLX_RED_SIZE, 1,
660                 GLX_GREEN_SIZE, 1,
661                 GLX_BLUE_SIZE, 1,
662                 GLX_DOUBLEBUFFER,
663                 GLX_DEPTH_SIZE, 1,
664                 None
665         };
666         XSetWindowAttributes attr;
667         unsigned long mask;
668         Window root;
669         XVisualInfo *visinfo;
670         int MajorVersion, MinorVersion;
671
672         if (!GL_OpenLibrary("libGL.so.1"))
673                 Sys_Error("Unable to load GL driver\n");
674
675         Cvar_RegisterVariable (&vid_dga);
676         Cvar_RegisterVariable (&vid_dga_mouseaccel);
677
678         if (!(vidx11_display = XOpenDisplay(NULL)))
679         {
680                 fprintf(stderr, "Error couldn't open the X display\n");
681                 exit(1);
682         }
683
684         scrnum = DefaultScreen(vidx11_display);
685         root = RootWindow(vidx11_display, scrnum);
686
687         // Get video mode list
688         MajorVersion = MinorVersion = 0;
689         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
690                 vidmode_ext = false;
691         else
692         {
693                 Con_Printf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
694                 vidmode_ext = true;
695         }
696
697         if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
698          || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
699          || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
700          || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
701          || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
702                 Sys_Error("glX functions not found in %s\n", gl_driver);
703
704         visinfo = NULL;
705 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
706 #if 0
707         if (!COM_CheckParm("-nogamma"))
708                 visinfo = qglXChooseVisual(vidx11_display, scrnum, gammaattrib);
709 #endif
710         if (!visinfo)
711         {
712                 visinfo = qglXChooseVisual(vidx11_display, scrnum, nogammaattrib);
713                 if (!visinfo)
714                 {
715                         Sys_Error("couldn't get an RGB, Double-buffered, Depth visual\n");
716                         exit(1);
717                 }
718         }
719
720         if (vidmode_ext)
721         {
722                 int best_fit, best_dist, dist, x, y;
723
724                 XF86VidModeGetAllModeLines(vidx11_display, scrnum, &num_vidmodes, &vidmodes);
725
726                 // Are we going fullscreen?  If so, let's change video mode
727                 if (fullscreen)
728                 {
729                         best_dist = 9999999;
730                         best_fit = -1;
731
732                         for (i = 0; i < num_vidmodes; i++)
733                         {
734                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
735                                         continue;
736
737                                 x = width - vidmodes[i]->hdisplay;
738                                 y = height - vidmodes[i]->vdisplay;
739                                 dist = (x * x) + (y * y);
740                                 if (dist < best_dist)
741                                 {
742                                         best_dist = dist;
743                                         best_fit = i;
744                                 }
745                         }
746
747                         if (best_fit != -1)
748                         {
749                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
750                                 // to width/height =, so the window will take the full area of
751                                 // the mode chosen
752                                 width = vidmodes[best_fit]->hdisplay;
753                                 height = vidmodes[best_fit]->vdisplay;
754
755                                 // change to the mode
756                                 XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[best_fit]);
757                                 vidmode_active = true;
758
759                                 // Move the viewport to top left
760                                 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
761                         }
762                         else
763                                 fullscreen = 0;
764                 }
765         }
766
767         // LordHavoc: save the visual for use in gamma ramp settings later
768         vidx11_visual = visinfo->visual;
769
770         /* window attributes */
771         attr.background_pixel = 0;
772         attr.border_pixel = 0;
773         // LordHavoc: save the colormap for later, too
774         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
775         attr.event_mask = X_MASK;
776         if (vidmode_active)
777         {
778                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
779                 attr.override_redirect = True;
780                 attr.backing_store = NotUseful;
781                 attr.save_under = False;
782         }
783         else
784                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
785
786         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
787         XStoreName(vidx11_display, win, gamename);
788         XMapWindow(vidx11_display, win);
789
790         // LordHavoc: making the close button on a window do the right thing
791         // seems to involve this mess, sigh...
792         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
793         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
794
795         if (vidmode_active)
796         {
797                 XMoveWindow(vidx11_display, win, 0, 0);
798                 XRaiseWindow(vidx11_display, win);
799                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
800                 XFlush(vidx11_display);
801                 // Move the viewport to top left
802                 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
803         }
804
805         XFlush(vidx11_display);
806
807         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
808
809         qglXMakeCurrent(vidx11_display, win, ctx);
810
811         scr_width = width;
812         scr_height = height;
813
814         if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
815                 Sys_Error("glGetString not found in %s", gl_driver);
816
817         gl_renderer = qglGetString(GL_RENDERER);
818         gl_vendor = qglGetString(GL_VENDOR);
819         gl_version = qglGetString(GL_VERSION);
820         gl_extensions = qglGetString(GL_EXTENSIONS);
821         gl_platform = "GLX";
822         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, scrnum);
823
824         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
825         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_video_sync", videosyncfuncs, "-novideosync", false);
826
827         InitSig(); // trap evil signals
828
829         vid_hidden = false;
830
831         GL_Init();
832
833         Con_SafePrintf ("Video mode %dx%d initialized.\n", width, height);
834 }
835
836 void Sys_SendKeyEvents(void)
837 {
838         HandleEvents();
839 }
840
841 void IN_Init(void)
842 {
843         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
844                 mouse_avail = false;
845 }
846
847 void IN_Shutdown(void)
848 {
849 }
850
851 /*
852 ===========
853 IN_Commands
854 ===========
855 */
856 void IN_Commands (void)
857 {
858 }
859
860 void IN_Move (usercmd_t *cmd)
861 {
862         if (mouse_avail)
863                 IN_Mouse(cmd, mouse_x, mouse_y);
864         mouse_x = 0;
865         mouse_y = 0;
866 }
867
868 static void *prjobj = NULL;
869
870 int GL_OpenLibrary(const char *name)
871 {
872         Con_Printf("Loading GL driver %s\n", name);
873         GL_CloseLibrary();
874         if (!(prjobj = dlopen(name, RTLD_LAZY)))
875         {
876                 Con_Printf("Unable to open symbol list for %s\n", name);
877                 return false;
878         }
879         strcpy(gl_driver, name);
880         return true;
881 }
882
883 void GL_CloseLibrary(void)
884 {
885         if (prjobj)
886                 dlclose(prjobj);
887         prjobj = NULL;
888         gl_driver[0] = 0;
889         qglXGetProcAddressARB = NULL;
890         gl_extensions = "";
891         gl_platform = "";
892         gl_platformextensions = "";
893 }
894
895 void *GL_GetProcAddress(const char *name)
896 {
897         void *p = NULL;
898         if (qglXGetProcAddressARB != NULL)
899                 p = (void *) qglXGetProcAddressARB(name);
900         if (p == NULL)
901                 p = (void *) dlsym(prjobj, name);
902         return p;
903 }