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