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