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