]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_glx.c
merged special SUNOS LDFLAGS_UNIXCL into LDFLAGS_SUNOSCL to eliminate an ifeq which...
[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 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
39 #include <X11/extensions/xf86dga.h>
40 #endif
41 #include <X11/extensions/xf86vmode.h>
42
43 #include "quakedef.h"
44
45 // Tell startup code that we have a client
46 int cl_available = true;
47
48 // note: if we used the XRandR extension we could support refresh rates
49 qboolean vid_supportrefreshrate = false;
50
51 //GLX prototypes
52 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
53 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
54 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
55 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
56 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
57 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
58
59 //GLX_ARB_get_proc_address
60 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
61
62 static dllfunction_t getprocaddressfuncs[] =
63 {
64         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
65         {NULL, NULL}
66 };
67
68 //GLX_SGI_swap_control
69 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
70
71 static dllfunction_t swapcontrolfuncs[] =
72 {
73         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
74         {NULL, NULL}
75 };
76
77 static Display *vidx11_display = NULL;
78 static int vidx11_screen;
79 static Window win;
80 static GLXContext ctx = NULL;
81
82 Atom wm_delete_window_atom;
83
84 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
85 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
86                     PointerMotionMask | ButtonMotionMask)
87 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
88                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
89                 LeaveWindowMask)
90
91
92 static qboolean mouse_avail = true;
93 static qboolean vid_usingmouse = false;
94 static qboolean vid_usingvsync = false;
95 static qboolean vid_usevsync = false;
96 static qboolean vid_x11_hardwaregammasupported = false;
97 static int vid_x11_gammarampsize = 0;
98 static float    mouse_x, mouse_y;
99 static int p_mouse_x, p_mouse_y;
100
101 #if !defined(__APPLE__) && !defined(SUNOS)
102 // FIXME: vid_dga_mouseaccel is poorly named, it is actually the multiplier for mouse movement, not an acceleration (which would be a power function or something)
103 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1", "make use of DGA mouse input"};
104 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1", "speed of mouse when using DGA mouse input"};
105 #endif
106
107 qboolean vidmode_ext = false;
108
109 static int win_x, win_y;
110
111 static XF86VidModeModeInfo init_vidmode;
112 static qboolean vid_isfullscreen = false;
113
114 static Visual *vidx11_visual;
115 static Colormap vidx11_colormap;
116
117 /*-----------------------------------------------------------------------*/
118
119 static int XLateKey(XKeyEvent *ev, char *ascii)
120 {
121         int key = 0;
122         char buf[64];
123         KeySym keysym, shifted;
124
125         keysym = XLookupKeysym (ev, 0);
126         XLookupString(ev, buf, sizeof buf, &shifted, 0);
127         *ascii = buf[0];
128
129         switch(keysym)
130         {
131                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
132                 case XK_Page_Up:         key = K_PGUP; break;
133
134                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
135                 case XK_Page_Down:       key = K_PGDN; break;
136
137                 case XK_KP_Home: key = K_KP_HOME; break;
138                 case XK_Home:    key = K_HOME; break;
139
140                 case XK_KP_End:  key = K_KP_END; break;
141                 case XK_End:     key = K_END; break;
142
143                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
144                 case XK_Left:    key = K_LEFTARROW; break;
145
146                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
147                 case XK_Right:  key = K_RIGHTARROW;             break;
148
149                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
150                 case XK_Down:    key = K_DOWNARROW; break;
151
152                 case XK_KP_Up:   key = K_KP_UPARROW; break;
153                 case XK_Up:              key = K_UPARROW;        break;
154
155                 case XK_Escape: key = K_ESCAPE;         break;
156
157                 case XK_KP_Enter: key = K_KP_ENTER;     break;
158                 case XK_Return: key = K_ENTER;           break;
159
160                 case XK_Tab:            key = K_TAB;                     break;
161
162                 case XK_F1:              key = K_F1;                            break;
163
164                 case XK_F2:              key = K_F2;                            break;
165
166                 case XK_F3:              key = K_F3;                            break;
167
168                 case XK_F4:              key = K_F4;                            break;
169
170                 case XK_F5:              key = K_F5;                            break;
171
172                 case XK_F6:              key = K_F6;                            break;
173
174                 case XK_F7:              key = K_F7;                            break;
175
176                 case XK_F8:              key = K_F8;                            break;
177
178                 case XK_F9:              key = K_F9;                            break;
179
180                 case XK_F10:            key = K_F10;                     break;
181
182                 case XK_F11:            key = K_F11;                     break;
183
184                 case XK_F12:            key = K_F12;                     break;
185
186                 case XK_BackSpace: key = K_BACKSPACE; break;
187
188                 case XK_KP_Delete: key = K_KP_DEL; break;
189                 case XK_Delete: key = K_DEL; break;
190
191                 case XK_Pause:  key = K_PAUSE;           break;
192
193                 case XK_Shift_L:
194                 case XK_Shift_R:        key = K_SHIFT;          break;
195
196                 case XK_Execute:
197                 case XK_Control_L:
198                 case XK_Control_R:      key = K_CTRL;            break;
199
200                 case XK_Alt_L:
201                 case XK_Meta_L:
202                 case XK_Alt_R:
203                 case XK_Meta_R: key = K_ALT;                    break;
204
205                 case XK_KP_Begin: key = K_KP_5; break;
206
207                 case XK_Insert:key = K_INS; break;
208                 case XK_KP_Insert: key = K_KP_INS; break;
209
210                 case XK_KP_Multiply: key = '*'; break;
211                 case XK_KP_Add:  key = K_KP_PLUS; break;
212                 case XK_KP_Subtract: key = K_KP_MINUS; break;
213                 case XK_KP_Divide: key = K_KP_SLASH; break;
214
215                 case XK_section:        key = '~'; break;
216
217                 default:
218                         if (keysym < 32)
219                                 break;
220
221                         if (keysym >= 'A' && keysym <= 'Z')
222                                 key = keysym - 'A' + 'a';
223                         else
224                                 key = keysym;
225
226                         break;
227         }
228
229         return key;
230 }
231
232 static Cursor CreateNullCursor(Display *display, Window root)
233 {
234         Pixmap cursormask;
235         XGCValues xgc;
236         GC gc;
237         XColor dummycolour;
238         Cursor cursor;
239
240         cursormask = XCreatePixmap(display, root, 1, 1, 1);
241         xgc.function = GXclear;
242         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
243         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
244         dummycolour.pixel = 0;
245         dummycolour.red = 0;
246         dummycolour.flags = 04;
247         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
248         XFreePixmap(display,cursormask);
249         XFreeGC(display,gc);
250         return cursor;
251 }
252
253 static void IN_Activate (qboolean grab)
254 {
255         if (!vidx11_display)
256                 return;
257         if (grab)
258         {
259                 if (!vid_usingmouse && mouse_avail && win)
260                 {
261                         XWindowAttributes attribs_1;
262                         XSetWindowAttributes attribs_2;
263
264                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
265                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
266                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
267
268                 // inviso cursor
269                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
270
271                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
272
273 #if !defined(__APPLE__) && !defined(SUNOS)
274                         if (vid_dga.integer)
275                         {
276                                 int MajorVersion, MinorVersion;
277
278                                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
279                                 {
280                                         // unable to query, probably not supported
281                                         Con_Print( "Failed to detect XF86DGA Mouse\n" );
282                                         Cvar_SetValueQuick(&vid_dga, 0);
283                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
284                                 }
285                                 else
286                                 {
287                                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
288                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
289                                 }
290                         }
291                         else
292 #endif
293                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
294
295                         XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
296
297                         mouse_x = mouse_y = 0;
298                         cl_ignoremousemove = true;
299                         vid_usingmouse = true;
300                 }
301         }
302         else
303         {
304                 if (vid_usingmouse)
305                 {
306 #if !defined(__APPLE__) && !defined(SUNOS)
307                         if (vid_dga.integer)
308                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
309 #endif
310
311                         XUngrabPointer(vidx11_display, CurrentTime);
312                         XUngrabKeyboard(vidx11_display, CurrentTime);
313
314                         // inviso cursor
315                         if (win)
316                                 XUndefineCursor(vidx11_display, win);
317
318                         cl_ignoremousemove = true;
319                         vid_usingmouse = false;
320                 }
321         }
322 }
323
324 static keynum_t buttonremap[18] =
325 {
326         K_MOUSE1,
327         K_MOUSE3,
328         K_MOUSE2,
329         K_MWHEELUP,
330         K_MWHEELDOWN,
331         K_MOUSE4,
332         K_MOUSE5,
333         K_MOUSE6,
334         K_MOUSE7,
335         K_MOUSE8,
336         K_MOUSE9,
337         K_MOUSE10,
338         K_MOUSE11,
339         K_MOUSE12,
340         K_MOUSE13,
341         K_MOUSE14,
342         K_MOUSE15,
343         K_MOUSE16,
344 };
345
346 static void HandleEvents(void)
347 {
348         XEvent event;
349         int key;
350         char ascii;
351         qboolean dowarp = false;
352
353         if (!vidx11_display)
354                 return;
355
356         while (XPending(vidx11_display))
357         {
358                 XNextEvent(vidx11_display, &event);
359
360                 switch (event.type)
361                 {
362                 case KeyPress:
363                         // key pressed
364                         key = XLateKey (&event.xkey, &ascii);
365                         Key_Event(key, ascii, true);
366                         break;
367
368                 case KeyRelease:
369                         // key released
370                         key = XLateKey (&event.xkey, &ascii);
371                         Key_Event(key, ascii, false);
372                         break;
373
374                 case MotionNotify:
375                         // mouse moved
376                         if (vid_usingmouse)
377                         {
378 #if !defined(__APPLE__) && !defined(SUNOS)
379                                 if (vid_dga.integer == 1)
380                                 {
381                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
382                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
383                                 }
384                                 else
385 #endif
386                                 {
387
388                                         if (!event.xmotion.send_event)
389                                         {
390                                                 mouse_x += event.xmotion.x - p_mouse_x;
391                                                 mouse_y += event.xmotion.y - p_mouse_y;
392                                                 if (abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
393                                                         dowarp = true;
394                                         }
395                                         p_mouse_x = event.xmotion.x;
396                                         p_mouse_y = event.xmotion.y;
397                                 }
398                         }
399                         //else
400                         //      ui_mouseupdate(event.xmotion.x, event.xmotion.y);
401                         break;
402
403                 case ButtonPress:
404                         // mouse button pressed
405                         if (event.xbutton.button <= 18)
406                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
407                         else
408                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
409                         break;
410
411                 case ButtonRelease:
412                         // mouse button released
413                         if (event.xbutton.button <= 18)
414                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
415                         else
416                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
417                         break;
418
419                 case CreateNotify:
420                         // window created
421                         win_x = event.xcreatewindow.x;
422                         win_y = event.xcreatewindow.y;
423                         break;
424
425                 case ConfigureNotify:
426                         // window changed size/location
427                         win_x = event.xconfigure.x;
428                         win_y = event.xconfigure.y;
429                         break;
430                 case DestroyNotify:
431                         // window has been destroyed
432                         Sys_Quit();
433                         break;
434                 case ClientMessage:
435                         // window manager messages
436                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
437                                 Sys_Quit();
438                         break;
439                 case MapNotify:
440                         // window restored
441                         vid_hidden = false;
442                         vid_activewindow = false;
443                         VID_RestoreSystemGamma();
444                         break;
445                 case UnmapNotify:
446                         // window iconified/rolledup/whatever
447                         vid_hidden = true;
448                         vid_activewindow = false;
449                         VID_RestoreSystemGamma();
450                         break;
451                 case FocusIn:
452                         // window is now the input focus
453                         vid_activewindow = true;
454                         break;
455                 case FocusOut:
456                         // window is no longer the input focus
457                         vid_activewindow = false;
458                         VID_RestoreSystemGamma();
459                         break;
460                 case EnterNotify:
461                         // mouse entered window
462                         break;
463                 case LeaveNotify:
464                         // mouse left window
465                         break;
466                 }
467         }
468
469         if (dowarp)
470         {
471                 /* move the mouse to the window center again */
472                 p_mouse_x = vid.width / 2;
473                 p_mouse_y = vid.height / 2;
474                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
475         }
476 }
477
478 static void *prjobj = NULL;
479
480 static void GL_CloseLibrary(void)
481 {
482         if (prjobj)
483                 dlclose(prjobj);
484         prjobj = NULL;
485         gl_driver[0] = 0;
486         qglXGetProcAddressARB = NULL;
487         gl_extensions = "";
488         gl_platform = "";
489         gl_platformextensions = "";
490 }
491
492 static int GL_OpenLibrary(const char *name)
493 {
494         Con_Printf("Loading OpenGL driver %s\n", name);
495         GL_CloseLibrary();
496         if (!(prjobj = dlopen(name, RTLD_LAZY)))
497         {
498                 Con_Printf("Unable to open symbol list for %s\n", name);
499                 return false;
500         }
501         strcpy(gl_driver, name);
502         return true;
503 }
504
505 void *GL_GetProcAddress(const char *name)
506 {
507         void *p = NULL;
508         if (qglXGetProcAddressARB != NULL)
509                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
510         if (p == NULL)
511                 p = (void *) dlsym(prjobj, name);
512         return p;
513 }
514
515 void VID_Shutdown(void)
516 {
517         if (!ctx || !vidx11_display)
518                 return;
519
520         if (vidx11_display)
521         {
522                 IN_Activate(false);
523                 VID_RestoreSystemGamma();
524
525                 // FIXME: glXDestroyContext here?
526                 if (vid_isfullscreen)
527                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
528                 if (win)
529                         XDestroyWindow(vidx11_display, win);
530                 XCloseDisplay(vidx11_display);
531         }
532         vid_hidden = true;
533         vid_isfullscreen = false;
534         vidx11_display = NULL;
535         win = 0;
536         ctx = NULL;
537
538         GL_CloseLibrary();
539         Key_ClearStates ();
540 }
541
542 void signal_handler(int sig)
543 {
544         Con_Printf("Received signal %d, exiting...\n", sig);
545         VID_RestoreSystemGamma();
546         Sys_Quit();
547         exit(0);
548 }
549
550 void InitSig(void)
551 {
552         signal(SIGHUP, signal_handler);
553         signal(SIGINT, signal_handler);
554         signal(SIGQUIT, signal_handler);
555         signal(SIGILL, signal_handler);
556         signal(SIGTRAP, signal_handler);
557         signal(SIGIOT, signal_handler);
558         signal(SIGBUS, signal_handler);
559         signal(SIGFPE, signal_handler);
560         signal(SIGSEGV, signal_handler);
561         signal(SIGTERM, signal_handler);
562 }
563
564 void VID_Finish (qboolean allowmousegrab)
565 {
566         qboolean vid_usemouse;
567
568         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
569         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
570         {
571                 vid_usingvsync = vid_usevsync;
572                 if (qglXSwapIntervalSGI (vid_usevsync))
573                         Con_Print("glXSwapIntervalSGI didn't accept the vid_vsync change, it will take effect on next vid_restart (GLX_SGI_swap_control does not allow turning off vsync)\n");
574         }
575
576 // handle the mouse state when windowed if that's changed
577         vid_usemouse = false;
578         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
579                 vid_usemouse = true;
580         if (!vid_activewindow)
581                 vid_usemouse = false;
582         if (vid_isfullscreen)
583                 vid_usemouse = true;
584         IN_Activate(vid_usemouse);
585
586         if (r_render.integer)
587         {
588                 if (r_speeds.integer || gl_finish.integer)
589                         qglFinish();
590                 qglXSwapBuffers(vidx11_display, win);
591         }
592
593         if (vid_x11_hardwaregammasupported)
594                 VID_UpdateGamma(false, vid_x11_gammarampsize);
595 }
596
597 int VID_SetGamma(unsigned short *ramps, int rampsize)
598 {
599         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
600 }
601
602 int VID_GetGamma(unsigned short *ramps, int rampsize)
603 {
604         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
605 }
606
607 void VID_Init(void)
608 {
609 #if !defined(__APPLE__) && !defined(SUNOS)
610         Cvar_RegisterVariable (&vid_dga);
611         Cvar_RegisterVariable (&vid_dga_mouseaccel);
612 #endif
613         InitSig(); // trap evil signals
614 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
615         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
616                 mouse_avail = false;
617 }
618
619 void VID_BuildGLXAttrib(int *attrib, int stencil)
620 {
621         *attrib++ = GLX_RGBA;
622         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
623         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
624         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
625         *attrib++ = GLX_DOUBLEBUFFER;
626         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
627         // if stencil is enabled, ask for alpha too
628         if (stencil)
629         {
630                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
631                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
632         }
633         *attrib++ = None;
634 }
635
636 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
637 {
638         int i;
639         int attrib[32];
640         XSetWindowAttributes attr;
641         unsigned long mask;
642         Window root;
643         XVisualInfo *visinfo;
644         int MajorVersion, MinorVersion;
645         const char *drivername;
646
647 #if defined(__APPLE__) && defined(__MACH__)
648         drivername = "/usr/X11R6/lib/libGL.1.dylib";
649 #else
650         drivername = "libGL.so.1";
651 #endif
652 // COMMANDLINEOPTION: Linux GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
653 // COMMANDLINEOPTION: BSD GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
654 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
655         i = COM_CheckParm("-gl_driver");
656         if (i && i < com_argc - 1)
657                 drivername = com_argv[i + 1];
658         if (!GL_OpenLibrary(drivername))
659         {
660                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
661                 return false;
662         }
663
664         if (!(vidx11_display = XOpenDisplay(NULL)))
665         {
666                 Con_Print("Couldn't open the X display\n");
667                 return false;
668         }
669
670         vidx11_screen = DefaultScreen(vidx11_display);
671         root = RootWindow(vidx11_display, vidx11_screen);
672
673         // Get video mode list
674         MajorVersion = MinorVersion = 0;
675         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
676                 vidmode_ext = false;
677         else
678         {
679                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
680                 vidmode_ext = true;
681         }
682
683         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
684          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
685          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
686          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
687          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
688          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
689         {
690                 Con_Printf("glX functions not found in %s\n", gl_driver);
691                 return false;
692         }
693
694         VID_BuildGLXAttrib(attrib, bpp == 32);
695         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
696         if (!visinfo)
697         {
698                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
699                 return false;
700         }
701
702         if (vidmode_ext)
703         {
704                 int best_fit, best_dist, dist, x, y;
705
706                 // Are we going fullscreen?  If so, let's change video mode
707                 if (fullscreen)
708                 {
709                         XF86VidModeModeLine *current_vidmode;
710                         XF86VidModeModeInfo **vidmodes;
711                         int num_vidmodes;
712
713                         // This nice hack comes from the SDL source code
714                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
715                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
716
717                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
718                         best_dist = 9999999;
719                         best_fit = -1;
720
721                         for (i = 0; i < num_vidmodes; i++)
722                         {
723                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
724                                         continue;
725
726                                 x = width - vidmodes[i]->hdisplay;
727                                 y = height - vidmodes[i]->vdisplay;
728                                 dist = (x * x) + (y * y);
729                                 if (dist < best_dist)
730                                 {
731                                         best_dist = dist;
732                                         best_fit = i;
733                                 }
734                         }
735
736                         if (best_fit != -1)
737                         {
738                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
739                                 // to width/height =, so the window will take the full area of
740                                 // the mode chosen
741                                 width = vidmodes[best_fit]->hdisplay;
742                                 height = vidmodes[best_fit]->vdisplay;
743
744                                 // change to the mode
745                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
746                                 vid_isfullscreen = true;
747
748                                 // Move the viewport to top left
749                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
750                         }
751                         else
752                                 fullscreen = 0;
753
754                         free(vidmodes);
755                 }
756         }
757
758         // LordHavoc: save the visual for use in gamma ramp settings later
759         vidx11_visual = visinfo->visual;
760
761         /* window attributes */
762         attr.background_pixel = 0;
763         attr.border_pixel = 0;
764         // LordHavoc: save the colormap for later, too
765         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
766         attr.event_mask = X_MASK;
767         if (vid_isfullscreen)
768         {
769                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
770                 attr.override_redirect = True;
771                 attr.backing_store = NotUseful;
772                 attr.save_under = False;
773         }
774         else
775                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
776
777         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
778         XStoreName(vidx11_display, win, gamename);
779         XMapWindow(vidx11_display, win);
780
781         // LordHavoc: making the close button on a window do the right thing
782         // seems to involve this mess, sigh...
783         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
784         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
785
786         if (vid_isfullscreen)
787         {
788                 XMoveWindow(vidx11_display, win, 0, 0);
789                 XRaiseWindow(vidx11_display, win);
790                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
791                 XFlush(vidx11_display);
792                 // Move the viewport to top left
793                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
794         }
795
796         //XSync(vidx11_display, False);
797
798         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
799         if (!ctx)
800         {
801                 Con_Printf ("glXCreateContext failed\n");
802                 return false;
803         }
804
805         if (!qglXMakeCurrent(vidx11_display, win, ctx))
806         {
807                 Con_Printf ("glXMakeCurrent failed\n");
808                 return false;
809         }
810
811         XSync(vidx11_display, False);
812
813         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
814         {
815                 Con_Printf ("glGetString not found in %s\n", gl_driver);
816                 return false;
817         }
818
819         gl_renderer = (const char *)qglGetString(GL_RENDERER);
820         gl_vendor = (const char *)qglGetString(GL_VENDOR);
821         gl_version = (const char *)qglGetString(GL_VERSION);
822         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
823         gl_platform = "GLX";
824         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
825
826         gl_videosyncavailable = false;
827
828 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
829 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
830 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
831         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
832 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
833 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
834 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
835         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
836
837         vid_usingmouse = false;
838         vid_usingvsync = false;
839         vid_hidden = false;
840         vid_activewindow = true;
841         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
842         GL_Init();
843         return true;
844 }
845
846 void Sys_SendKeyEvents(void)
847 {
848         HandleEvents();
849 }
850
851 void IN_Move (void)
852 {
853         if (mouse_avail)
854         {
855                 in_mouse_x = mouse_x;
856                 in_mouse_y = mouse_y;
857         }
858         mouse_x = 0;
859         mouse_y = 0;
860 }