]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_glx.c
add a new key dest key_menu_grabbed that behaves like key_menu, but also passes funct...
[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 <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 "quakedef.h"
29
30 #include <X11/keysym.h>
31 #include <X11/cursorfont.h>
32 #include <X11/xpm.h>
33
34 #include <X11/extensions/XShm.h>
35 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
36 #include <X11/extensions/xf86dga.h>
37 #endif
38 #include <X11/extensions/xf86vmode.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_ignoremousemoves = 2;
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_ignoremousemoves = 2;
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                         if(vid_resizable.integer < 2)
417                         {
418                                 vid.width = event.xconfigure.width;
419                                 vid.height = event.xconfigure.height;
420                         }
421                         break;
422                 case DestroyNotify:
423                         // window has been destroyed
424                         Sys_Quit(0);
425                         break;
426                 case ClientMessage:
427                         // window manager messages
428                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
429                                 Sys_Quit(0);
430                         break;
431                 case MapNotify:
432                         // window restored
433                         vid_hidden = false;
434                         VID_RestoreSystemGamma();
435                         break;
436                 case UnmapNotify:
437                         // window iconified/rolledup/whatever
438                         vid_hidden = true;
439                         VID_RestoreSystemGamma();
440                         break;
441                 case FocusIn:
442                         // window is now the input focus
443                         vid_activewindow = true;
444                         break;
445                 case FocusOut:
446                         // window is no longer the input focus
447                         vid_activewindow = false;
448                         VID_RestoreSystemGamma();
449                         break;
450                 case EnterNotify:
451                         // mouse entered window
452                         break;
453                 case LeaveNotify:
454                         // mouse left window
455                         break;
456                 }
457         }
458
459         if (dowarp)
460         {
461                 /* move the mouse to the window center again */
462                 p_mouse_x = vid.width / 2;
463                 p_mouse_y = vid.height / 2;
464                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
465         }
466 }
467
468 static void *prjobj = NULL;
469
470 static void GL_CloseLibrary(void)
471 {
472         if (prjobj)
473                 dlclose(prjobj);
474         prjobj = NULL;
475         gl_driver[0] = 0;
476         qglXGetProcAddressARB = NULL;
477         gl_extensions = "";
478         gl_platform = "";
479         gl_platformextensions = "";
480 }
481
482 static int GL_OpenLibrary(const char *name)
483 {
484         Con_Printf("Loading OpenGL driver %s\n", name);
485         GL_CloseLibrary();
486         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
487         {
488                 Con_Printf("Unable to open symbol list for %s\n", name);
489                 return false;
490         }
491         strlcpy(gl_driver, name, sizeof(gl_driver));
492         return true;
493 }
494
495 void *GL_GetProcAddress(const char *name)
496 {
497         void *p = NULL;
498         if (qglXGetProcAddressARB != NULL)
499                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
500         if (p == NULL)
501                 p = (void *) dlsym(prjobj, name);
502         return p;
503 }
504
505 void VID_Shutdown(void)
506 {
507         if (!ctx || !vidx11_display)
508                 return;
509
510         if (vidx11_display)
511         {
512                 IN_Activate(false);
513                 VID_RestoreSystemGamma();
514
515                 // FIXME: glXDestroyContext here?
516                 if (vid_isfullscreen)
517                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
518                 if (win)
519                         XDestroyWindow(vidx11_display, win);
520                 XCloseDisplay(vidx11_display);
521         }
522         vid_hidden = true;
523         vid_isfullscreen = false;
524         vidx11_display = NULL;
525         win = 0;
526         ctx = NULL;
527
528         GL_CloseLibrary();
529         Key_ClearStates ();
530 }
531
532 void signal_handler(int sig)
533 {
534         Con_Printf("Received signal %d, exiting...\n", sig);
535         VID_RestoreSystemGamma();
536         Sys_Quit(1);
537 }
538
539 void InitSig(void)
540 {
541         signal(SIGHUP, signal_handler);
542         signal(SIGINT, signal_handler);
543         signal(SIGQUIT, signal_handler);
544         signal(SIGILL, signal_handler);
545         signal(SIGTRAP, signal_handler);
546         signal(SIGIOT, signal_handler);
547         signal(SIGBUS, signal_handler);
548         signal(SIGFPE, signal_handler);
549         signal(SIGSEGV, signal_handler);
550         signal(SIGTERM, signal_handler);
551 }
552
553 void VID_Finish (qboolean allowmousegrab)
554 {
555         qboolean vid_usemouse;
556
557         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
558         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
559         {
560                 vid_usingvsync = vid_usevsync;
561                 if (qglXSwapIntervalSGI (vid_usevsync))
562                         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");
563         }
564
565         // handle the mouse state when windowed if that's changed
566         vid_usemouse = false;
567         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
568                 vid_usemouse = true;
569         if (!vid_activewindow)
570                 vid_usemouse = false;
571         if (vid_isfullscreen)
572                 vid_usemouse = true;
573         IN_Activate(vid_usemouse);
574
575         if (r_render.integer)
576         {
577                 CHECKGLERROR
578                 if (r_speeds.integer || gl_finish.integer)
579                 {
580                         qglFinish();CHECKGLERROR
581                 }
582                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
583         }
584
585         if (vid_x11_hardwaregammasupported)
586                 VID_UpdateGamma(false, vid_x11_gammarampsize);
587 }
588
589 int VID_SetGamma(unsigned short *ramps, int rampsize)
590 {
591         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
592 }
593
594 int VID_GetGamma(unsigned short *ramps, int rampsize)
595 {
596         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
597 }
598
599 void VID_Init(void)
600 {
601 #if !defined(__APPLE__) && !defined(SUNOS)
602         Cvar_RegisterVariable (&vid_dgamouse);
603 #endif
604         InitSig(); // trap evil signals
605 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
606         if (COM_CheckParm ("-nomouse"))
607                 mouse_avail = false;
608 }
609
610 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer)
611 {
612         *attrib++ = GLX_RGBA;
613         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
614         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
615         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
616         *attrib++ = GLX_DOUBLEBUFFER;
617         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
618         // if stencil is enabled, ask for alpha too
619         if (stencil)
620         {
621                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
622                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
623         }
624         if (stereobuffer)
625                 *attrib++ = GLX_STEREO;
626         *attrib++ = None;
627 }
628
629 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
630 {
631         int i;
632         int attrib[32];
633         XSetWindowAttributes attr;
634         XClassHint *clshints;
635         XWMHints *wmhints;
636         XSizeHints *szhints;
637         unsigned long mask;
638         Window root;
639         XVisualInfo *visinfo;
640         int MajorVersion, MinorVersion;
641         const char *drivername;
642
643 #if defined(__APPLE__) && defined(__MACH__)
644         drivername = "/usr/X11R6/lib/libGL.1.dylib";
645 #else
646         drivername = "libGL.so.1";
647 #endif
648 // 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
649 // 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
650 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
651         i = COM_CheckParm("-gl_driver");
652         if (i && i < com_argc - 1)
653                 drivername = com_argv[i + 1];
654         if (!GL_OpenLibrary(drivername))
655         {
656                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
657                 return false;
658         }
659
660         if (!(vidx11_display = XOpenDisplay(NULL)))
661         {
662                 Con_Print("Couldn't open the X display\n");
663                 return false;
664         }
665
666         vidx11_screen = DefaultScreen(vidx11_display);
667         root = RootWindow(vidx11_display, vidx11_screen);
668
669         // Get video mode list
670         MajorVersion = MinorVersion = 0;
671         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
672                 vidmode_ext = false;
673         else
674         {
675                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
676                 vidmode_ext = true;
677         }
678
679         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
680          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
681          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
682          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
683          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
684          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
685         {
686                 Con_Printf("glX functions not found in %s\n", gl_driver);
687                 return false;
688         }
689
690         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer);
691         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
692         if (!visinfo)
693         {
694                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
695                 return false;
696         }
697
698         if (vidmode_ext)
699         {
700                 int best_fit, best_dist, dist, x, y;
701
702                 // Are we going fullscreen?  If so, let's change video mode
703                 if (fullscreen)
704                 {
705                         XF86VidModeModeLine *current_vidmode;
706                         XF86VidModeModeInfo **vidmodes;
707                         int num_vidmodes;
708
709                         // This nice hack comes from the SDL source code
710                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
711                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
712
713                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
714                         best_dist = 9999999;
715                         best_fit = -1;
716
717                         for (i = 0; i < num_vidmodes; i++)
718                         {
719                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
720                                         continue;
721
722                                 x = width - vidmodes[i]->hdisplay;
723                                 y = height - vidmodes[i]->vdisplay;
724                                 dist = (x * x) + (y * y);
725                                 if (dist < best_dist)
726                                 {
727                                         best_dist = dist;
728                                         best_fit = i;
729                                 }
730                         }
731
732                         if (best_fit != -1)
733                         {
734                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
735                                 // to width/height =, so the window will take the full area of
736                                 // the mode chosen
737                                 width = vidmodes[best_fit]->hdisplay;
738                                 height = vidmodes[best_fit]->vdisplay;
739
740                                 // change to the mode
741                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
742                                 vid_isfullscreen = true;
743
744                                 // Move the viewport to top left
745                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
746                         }
747                         else
748                                 fullscreen = 0;
749
750                         free(vidmodes);
751                 }
752         }
753
754         // LordHavoc: save the visual for use in gamma ramp settings later
755         vidx11_visual = visinfo->visual;
756
757         /* window attributes */
758         attr.background_pixel = 0;
759         attr.border_pixel = 0;
760         // LordHavoc: save the colormap for later, too
761         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
762         attr.event_mask = X_MASK;
763         if (vid_isfullscreen)
764         {
765                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
766                 attr.override_redirect = True;
767                 attr.backing_store = NotUseful;
768                 attr.save_under = False;
769         }
770         else
771                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
772
773         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
774
775         wmhints = XAllocWMHints();
776         if(XpmCreatePixmapFromData(vidx11_display, win,
777                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
778                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
779                 wmhints->flags |= IconPixmapHint | IconMaskHint;
780
781         clshints = XAllocClassHint();
782         clshints->res_name = strdup(gamename);
783         clshints->res_class = strdup("DarkPlaces");
784
785         szhints = XAllocSizeHints();
786         if(vid_resizable.integer == 0)
787         {
788                 szhints->min_width = szhints->max_width = width;
789                 szhints->min_height = szhints->max_height = height;
790                 szhints->flags |= PMinSize | PMaxSize;
791         }
792
793         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
794         XFree(clshints);
795         XFree(wmhints);
796         XFree(szhints);
797         //XStoreName(vidx11_display, win, gamename);
798         XMapWindow(vidx11_display, win);
799
800         // LordHavoc: making the close button on a window do the right thing
801         // seems to involve this mess, sigh...
802         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
803         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
804
805         if (vid_isfullscreen)
806         {
807                 XMoveWindow(vidx11_display, win, 0, 0);
808                 XRaiseWindow(vidx11_display, win);
809                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
810                 XFlush(vidx11_display);
811                 // Move the viewport to top left
812                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
813         }
814
815         //XSync(vidx11_display, False);
816
817         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
818         if (!ctx)
819         {
820                 Con_Printf ("glXCreateContext failed\n");
821                 return false;
822         }
823
824         if (!qglXMakeCurrent(vidx11_display, win, ctx))
825         {
826                 Con_Printf ("glXMakeCurrent failed\n");
827                 return false;
828         }
829
830         XSync(vidx11_display, False);
831
832         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
833         {
834                 Con_Printf ("glGetString not found in %s\n", gl_driver);
835                 return false;
836         }
837
838         gl_renderer = (const char *)qglGetString(GL_RENDERER);
839         gl_vendor = (const char *)qglGetString(GL_VENDOR);
840         gl_version = (const char *)qglGetString(GL_VERSION);
841         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
842         gl_platform = "GLX";
843         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
844
845         gl_videosyncavailable = false;
846
847 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
848 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
849 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
850         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
851 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
852 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
853 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
854         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
855
856         vid_usingmouse = false;
857         vid_usingvsync = false;
858         vid_hidden = false;
859         vid_activewindow = true;
860         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
861 #if !defined(__APPLE__) && !defined(SUNOS)
862         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
863         if (!vid_x11_dgasupported)
864                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
865 #endif
866         GL_Init();
867         return true;
868 }
869
870 void Sys_SendKeyEvents(void)
871 {
872         static qboolean sound_active = true;
873
874         // enable/disable sound on focus gain/loss
875         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
876         {
877                 if (!sound_active)
878                 {
879                         S_UnblockSound ();
880                         sound_active = true;
881                 }
882         }
883         else
884         {
885                 if (sound_active)
886                 {
887                         S_BlockSound ();
888                         sound_active = false;
889                 }
890         }
891
892         HandleEvents();
893 }
894
895 void IN_Move (void)
896 {
897         if (mouse_avail)
898         {
899                 in_mouse_x = mouse_x;
900                 in_mouse_y = mouse_y;
901         }
902         mouse_x = 0;
903         mouse_y = 0;
904 }