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