]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_glx.c
try to improve netwm fullscreen mode
[xonotic/darkplaces.git] / vid_glx.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20 #include <signal.h>
21
22 #include <dlfcn.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <X11/Xatom.h>
27 #include <X11/XKBlib.h> // TODO possibly ifdef this out on non-supporting systems... Solaris (as always)?
28 #include <GL/glx.h>
29
30 #include "quakedef.h"
31
32 #include <X11/keysym.h>
33 #include <X11/cursorfont.h>
34 #include <X11/xpm.h>
35
36 #include <X11/extensions/XShm.h>
37 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
38 #include <X11/extensions/xf86dga.h>
39 #endif
40 #include <X11/extensions/xf86vmode.h>
41
42 #include "nexuiz.xpm"
43 #include "darkplaces.xpm"
44
45 // Tell startup code that we have a client
46 int cl_available = true;
47
48 // note: if we used the XRandR extension we could support refresh rates
49 qboolean vid_supportrefreshrate = false;
50
51 //GLX prototypes
52 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
53 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
54 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
55 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
56 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
57 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
58
59 //GLX_ARB_get_proc_address
60 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
61
62 static dllfunction_t getprocaddressfuncs[] =
63 {
64         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
65         {NULL, NULL}
66 };
67
68 //GLX_SGI_swap_control
69 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
70
71 static dllfunction_t swapcontrolfuncs[] =
72 {
73         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
74         {NULL, NULL}
75 };
76
77 static Display *vidx11_display = NULL;
78 static int vidx11_screen;
79 static Window win;
80 static GLXContext ctx = NULL;
81
82 Atom wm_delete_window_atom;
83
84 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
85 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
86                     PointerMotionMask | ButtonMotionMask)
87 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
88                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
89                 LeaveWindowMask)
90
91
92 static qboolean mouse_avail = true;
93 static qboolean vid_usingmousegrab = false;
94 static qboolean vid_usingmouse = false;
95 static qboolean vid_usinghidecursor = false;
96 static qboolean vid_usingvsync = false;
97 static qboolean vid_usevsync = false;
98 static qboolean vid_x11_hardwaregammasupported = false;
99 static qboolean vid_x11_dgasupported = false;
100 static int vid_x11_gammarampsize = 0;
101
102 #if !defined(__APPLE__) && !defined(SUNOS)
103 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "0", "make use of DGA mouse input"};
104 static qboolean vid_usingdgamouse = false;
105 #endif
106 cvar_t vid_netwmfullscreen = {CVAR_SAVE, "vid_netwmfullscreen", "0", "make use _NET_WM_STATE_FULLSCREEN; turn this off if fullscreen does not work for you"};
107
108 qboolean vidmode_ext = false;
109
110 static int win_x, win_y;
111
112 static XF86VidModeModeInfo init_vidmode, game_vidmode;
113 static qboolean vid_isfullscreen = false;
114 static qboolean vid_isnetwmfullscreen = false;
115
116 static Visual *vidx11_visual;
117 static Colormap vidx11_colormap;
118
119 /*-----------------------------------------------------------------------*/
120
121 static int XLateKey(XKeyEvent *ev, char *ascii)
122 {
123         int key = 0;
124         char buf[64];
125         KeySym keysym, shifted;
126
127         keysym = XLookupKeysym (ev, 0);
128         XLookupString(ev, buf, sizeof buf, &shifted, 0);
129         *ascii = buf[0];
130
131         switch(keysym)
132         {
133                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
134                 case XK_Page_Up:         key = K_PGUP; break;
135
136                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
137                 case XK_Page_Down:       key = K_PGDN; break;
138
139                 case XK_KP_Home: key = K_KP_HOME; break;
140                 case XK_Home:    key = K_HOME; break;
141
142                 case XK_KP_End:  key = K_KP_END; break;
143                 case XK_End:     key = K_END; break;
144
145                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
146                 case XK_Left:    key = K_LEFTARROW; break;
147
148                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
149                 case XK_Right:  key = K_RIGHTARROW;             break;
150
151                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
152                 case XK_Down:    key = K_DOWNARROW; break;
153
154                 case XK_KP_Up:   key = K_KP_UPARROW; break;
155                 case XK_Up:              key = K_UPARROW;        break;
156
157                 case XK_Escape: key = K_ESCAPE;         break;
158
159                 case XK_KP_Enter: key = K_KP_ENTER;     break;
160                 case XK_Return: key = K_ENTER;           break;
161
162                 case XK_Tab:            key = K_TAB;                     break;
163
164                 case XK_F1:              key = K_F1;                            break;
165
166                 case XK_F2:              key = K_F2;                            break;
167
168                 case XK_F3:              key = K_F3;                            break;
169
170                 case XK_F4:              key = K_F4;                            break;
171
172                 case XK_F5:              key = K_F5;                            break;
173
174                 case XK_F6:              key = K_F6;                            break;
175
176                 case XK_F7:              key = K_F7;                            break;
177
178                 case XK_F8:              key = K_F8;                            break;
179
180                 case XK_F9:              key = K_F9;                            break;
181
182                 case XK_F10:            key = K_F10;                     break;
183
184                 case XK_F11:            key = K_F11;                     break;
185
186                 case XK_F12:            key = K_F12;                     break;
187
188                 case XK_BackSpace: key = K_BACKSPACE; break;
189
190                 case XK_KP_Delete: key = K_KP_DEL; break;
191                 case XK_Delete: key = K_DEL; break;
192
193                 case XK_Pause:  key = K_PAUSE;           break;
194
195                 case XK_Shift_L:
196                 case XK_Shift_R:        key = K_SHIFT;          break;
197
198                 case XK_Execute:
199                 case XK_Control_L:
200                 case XK_Control_R:      key = K_CTRL;            break;
201
202                 case XK_Alt_L:
203                 case XK_Meta_L:
204                 case XK_ISO_Level3_Shift:
205                 case XK_Alt_R:
206                 case XK_Meta_R: key = K_ALT;                    break;
207
208                 case XK_KP_Begin: key = K_KP_5; break;
209
210                 case XK_Insert:key = K_INS; break;
211                 case XK_KP_Insert: key = K_KP_INS; break;
212
213                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
214                 case XK_KP_Add:  key = K_KP_PLUS; break;
215                 case XK_KP_Subtract: key = K_KP_MINUS; break;
216                 case XK_KP_Divide: key = K_KP_SLASH; break;
217
218                 case XK_section:        key = '~'; break;
219
220                 default:
221                         if (keysym < 32)
222                                 break;
223
224                         if (keysym >= 'A' && keysym <= 'Z')
225                                 key = keysym - 'A' + 'a';
226                         else
227                                 key = keysym;
228
229                         break;
230         }
231
232         return key;
233 }
234
235 static Cursor CreateNullCursor(Display *display, Window root)
236 {
237         Pixmap cursormask;
238         XGCValues xgc;
239         GC gc;
240         XColor dummycolour;
241         Cursor cursor;
242
243         cursormask = XCreatePixmap(display, root, 1, 1, 1);
244         xgc.function = GXclear;
245         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
246         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
247         dummycolour.pixel = 0;
248         dummycolour.red = 0;
249         dummycolour.flags = 04;
250         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
251         XFreePixmap(display,cursormask);
252         XFreeGC(display,gc);
253         return cursor;
254 }
255
256 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
257 {
258         static int originalmouseparms_num;
259         static int originalmouseparms_denom;
260         static int originalmouseparms_threshold;
261         static qboolean restore_spi;
262
263 #if !defined(__APPLE__) && !defined(SUNOS)
264         qboolean usedgamouse;
265 #endif
266
267         if (!vidx11_display || !win)
268                 return;
269
270         if (relative)
271                 fullscreengrab = true;
272
273         if (!mouse_avail)
274                 fullscreengrab = relative = hidecursor = false;
275
276 #if !defined(__APPLE__) && !defined(SUNOS)
277         usedgamouse = relative && vid_dgamouse.integer;
278         if (!vid_x11_dgasupported)
279                 usedgamouse = false;
280         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
281                 VID_SetMouse(false, false, false); // ungrab first!
282 #endif
283
284         if (vid_usingmousegrab != fullscreengrab)
285         {
286                 vid_usingmousegrab = fullscreengrab;
287                 cl_ignoremousemoves = 2;
288                 if (fullscreengrab)
289                 {
290                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
291                         if (vid_grabkeyboard.integer || (vid_isfullscreen && !vid_isnetwmfullscreen))
292                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
293                 }
294                 else
295                 {
296                         XUngrabPointer(vidx11_display, CurrentTime);
297                         XUngrabKeyboard(vidx11_display, CurrentTime);
298                 }
299         }
300
301         if (relative)
302         {
303                 if (!vid_usingmouse)
304                 {
305                         XWindowAttributes attribs_1;
306                         XSetWindowAttributes attribs_2;
307
308                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
309                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
310                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
311
312 #if !defined(__APPLE__) && !defined(SUNOS)
313                         vid_usingdgamouse = usedgamouse;
314                         if (usedgamouse)
315                         {
316                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
317                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
318                         }
319                         else
320 #endif
321                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
322
323 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
324 #if !defined(__APPLE__) && !defined(SUNOS)
325                         if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
326 #else
327                         if (!COM_CheckParm ("-noforcemparms"))
328 #endif
329                         {
330                                 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
331                                 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
332                                 restore_spi = true;
333                         }
334                         else
335                                 restore_spi = false;
336
337                         cl_ignoremousemoves = 2;
338                         vid_usingmouse = true;
339                 }
340         }
341         else
342         {
343                 if (vid_usingmouse)
344                 {
345 #if !defined(__APPLE__) && !defined(SUNOS)
346                         if (vid_usingdgamouse)
347                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
348                         vid_usingdgamouse = false;
349 #endif
350                         cl_ignoremousemoves = 2;
351
352                         if (restore_spi)
353                                 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
354                         restore_spi = false;
355
356                         vid_usingmouse = false;
357                 }
358         }
359
360         if (vid_usinghidecursor != hidecursor)
361         {
362                 vid_usinghidecursor = hidecursor;
363                 if (hidecursor)
364                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
365                 else
366                         XUndefineCursor(vidx11_display, win);
367         }
368 }
369
370 static keynum_t buttonremap[18] =
371 {
372         K_MOUSE1,
373         K_MOUSE3,
374         K_MOUSE2,
375         K_MWHEELUP,
376         K_MWHEELDOWN,
377         K_MOUSE4,
378         K_MOUSE5,
379         K_MOUSE6,
380         K_MOUSE7,
381         K_MOUSE8,
382         K_MOUSE9,
383         K_MOUSE10,
384         K_MOUSE11,
385         K_MOUSE12,
386         K_MOUSE13,
387         K_MOUSE14,
388         K_MOUSE15,
389         K_MOUSE16,
390 };
391
392 static void HandleEvents(void)
393 {
394         XEvent event;
395         int key;
396         char ascii;
397         qboolean dowarp = false;
398
399         if (!vidx11_display)
400                 return;
401
402         while (XPending(vidx11_display))
403         {
404                 XNextEvent(vidx11_display, &event);
405
406                 switch (event.type)
407                 {
408                 case KeyPress:
409                         // key pressed
410                         key = XLateKey (&event.xkey, &ascii);
411                         Key_Event(key, ascii, true);
412                         break;
413
414                 case KeyRelease:
415                         // key released
416                         key = XLateKey (&event.xkey, &ascii);
417                         Key_Event(key, ascii, false);
418                         break;
419
420                 case MotionNotify:
421                         // mouse moved
422                         if (vid_usingmouse)
423                         {
424 #if !defined(__APPLE__) && !defined(SUNOS)
425                                 if (vid_usingdgamouse)
426                                 {
427                                         in_mouse_x += event.xmotion.x_root;
428                                         in_mouse_y += event.xmotion.y_root;
429                                 }
430                                 else
431 #endif
432                                 {
433                                         if (!event.xmotion.send_event)
434                                         {
435                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
436                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
437                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
438                                                 if (vid_stick_mouse.integer || abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
439                                                         dowarp = true;
440                                         }
441                                 }
442                         }
443                         in_windowmouse_x = event.xmotion.x;
444                         in_windowmouse_y = event.xmotion.y;
445                         break;
446
447                 case ButtonPress:
448                         // mouse button pressed
449                         if (event.xbutton.button <= 18)
450                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
451                         else
452                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
453                         break;
454
455                 case ButtonRelease:
456                         // mouse button released
457                         if (event.xbutton.button <= 18)
458                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
459                         else
460                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
461                         break;
462
463                 case CreateNotify:
464                         // window created
465                         win_x = event.xcreatewindow.x;
466                         win_y = event.xcreatewindow.y;
467                         break;
468
469                 case ConfigureNotify:
470                         // window changed size/location
471                         win_x = event.xconfigure.x;
472                         win_y = event.xconfigure.y;
473                         if(vid_resizable.integer < 2)
474                         {
475                                 vid.width = event.xconfigure.width;
476                                 vid.height = event.xconfigure.height;
477                         }
478                         break;
479                 case DestroyNotify:
480                         // window has been destroyed
481                         Sys_Quit(0);
482                         break;
483                 case ClientMessage:
484                         // window manager messages
485                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
486                                 Sys_Quit(0);
487                         break;
488                 case MapNotify:
489                         if (vid_isfullscreen && !vid_isnetwmfullscreen)
490                                 break;
491                         // window restored
492                         vid_hidden = false;
493                         VID_RestoreSystemGamma();
494
495                         if(vid_isfullscreen)
496                         {
497                                 Atom net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
498                                 Atom net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
499
500                                 // set our video mode
501                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &game_vidmode);
502
503                                 // reenter fullscreen
504                                 XChangeProperty(vidx11_display, win, net_wm_state_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *) &net_wm_state_fullscreen_atom, 1);
505
506                                 // Move the viewport to top left
507                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
508
509                                 // Move the window to the right place
510                                 XMoveWindow(vidx11_display, win, 0, 0);
511                                 XRaiseWindow(vidx11_display, win);
512                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
513                                 XFlush(vidx11_display);
514                         }
515
516                         break;
517                 case UnmapNotify:
518                         if (vid_isfullscreen && !vid_isnetwmfullscreen)
519                                 break;
520                         // window iconified/rolledup/whatever
521                         vid_hidden = true;
522                         VID_RestoreSystemGamma();
523
524                         if(vid_isfullscreen)
525                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
526
527                         break;
528                 case FocusIn:
529                         if (vid_isfullscreen && !vid_isnetwmfullscreen)
530                                 break;
531                         // window is now the input focus
532                         vid_activewindow = true;
533                         break;
534                 case FocusOut:
535                         if (vid_isfullscreen && !vid_isnetwmfullscreen)
536                                 break;
537                         // window is no longer the input focus
538                         vid_activewindow = false;
539                         VID_RestoreSystemGamma();
540
541                         if(vid_isfullscreen)
542                                 XUnmapWindow(vidx11_display, win);
543                                 // iconify netwm fullscreen window when it loses focus
544                                 // when the user selects it in the taskbar, the window manager will map it again and send MapNotify
545
546                         break;
547                 case EnterNotify:
548                         // mouse entered window
549                         break;
550                 case LeaveNotify:
551                         // mouse left window
552                         break;
553                 }
554         }
555
556         if (dowarp)
557         {
558                 /* move the mouse to the window center again */
559                 // we'll catch the warp motion by its send_event flag, updating the
560                 // stored mouse position without adding any delta motion
561                 XEvent event;
562                 event.type = MotionNotify;
563                 event.xmotion.display = vidx11_display;
564                 event.xmotion.window = win;
565                 event.xmotion.x = vid.width / 2;
566                 event.xmotion.y = vid.height / 2;
567                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
568                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
569         }
570 }
571
572 static void *prjobj = NULL;
573
574 static void GL_CloseLibrary(void)
575 {
576         if (prjobj)
577                 dlclose(prjobj);
578         prjobj = NULL;
579         gl_driver[0] = 0;
580         qglXGetProcAddressARB = NULL;
581         gl_extensions = "";
582         gl_platform = "";
583         gl_platformextensions = "";
584 }
585
586 static int GL_OpenLibrary(const char *name)
587 {
588         Con_Printf("Loading OpenGL driver %s\n", name);
589         GL_CloseLibrary();
590         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
591         {
592                 Con_Printf("Unable to open symbol list for %s\n", name);
593                 return false;
594         }
595         strlcpy(gl_driver, name, sizeof(gl_driver));
596         return true;
597 }
598
599 void *GL_GetProcAddress(const char *name)
600 {
601         void *p = NULL;
602         if (qglXGetProcAddressARB != NULL)
603                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
604         if (p == NULL)
605                 p = (void *) dlsym(prjobj, name);
606         return p;
607 }
608
609 void VID_Shutdown(void)
610 {
611         if (!ctx || !vidx11_display)
612                 return;
613
614         VID_SetMouse(false, false, false);
615         VID_RestoreSystemGamma();
616
617         // FIXME: glXDestroyContext here?
618         if (vid_isfullscreen)
619                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
620         if (win)
621                 XDestroyWindow(vidx11_display, win);
622         XCloseDisplay(vidx11_display);
623
624         vid_hidden = true;
625         vid_isfullscreen = false;
626         vid_isnetwmfullscreen = false;
627         vidx11_display = NULL;
628         win = 0;
629         ctx = NULL;
630
631         GL_CloseLibrary();
632         Key_ClearStates ();
633 }
634
635 void signal_handler(int sig)
636 {
637         Con_Printf("Received signal %d, exiting...\n", sig);
638         VID_RestoreSystemGamma();
639         Sys_Quit(1);
640 }
641
642 void InitSig(void)
643 {
644         signal(SIGHUP, signal_handler);
645         signal(SIGINT, signal_handler);
646         signal(SIGQUIT, signal_handler);
647         signal(SIGILL, signal_handler);
648         signal(SIGTRAP, signal_handler);
649         signal(SIGIOT, signal_handler);
650         signal(SIGBUS, signal_handler);
651         signal(SIGFPE, signal_handler);
652         signal(SIGSEGV, signal_handler);
653         signal(SIGTERM, signal_handler);
654 }
655
656 void VID_Finish (void)
657 {
658         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
659         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
660         {
661                 vid_usingvsync = vid_usevsync;
662                 if (qglXSwapIntervalSGI (vid_usevsync))
663                         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");
664         }
665
666         if (r_render.integer)
667         {
668                 CHECKGLERROR
669                 if (r_speeds.integer || gl_finish.integer)
670                 {
671                         qglFinish();CHECKGLERROR
672                 }
673                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
674         }
675
676         if (vid_x11_hardwaregammasupported)
677                 VID_UpdateGamma(false, vid_x11_gammarampsize);
678 }
679
680 int VID_SetGamma(unsigned short *ramps, int rampsize)
681 {
682         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
683 }
684
685 int VID_GetGamma(unsigned short *ramps, int rampsize)
686 {
687         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
688 }
689
690 void VID_Init(void)
691 {
692 #if !defined(__APPLE__) && !defined(SUNOS)
693         Cvar_RegisterVariable (&vid_dgamouse);
694 #endif
695         Cvar_RegisterVariable (&vid_netwmfullscreen);
696         InitSig(); // trap evil signals
697 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
698         if (COM_CheckParm ("-nomouse"))
699                 mouse_avail = false;
700 }
701
702 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
703 {
704         *attrib++ = GLX_RGBA;
705         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
706         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
707         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
708         *attrib++ = GLX_DOUBLEBUFFER;
709         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
710         // if stencil is enabled, ask for alpha too
711         if (stencil)
712         {
713                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
714                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
715         }
716         if (stereobuffer)
717                 *attrib++ = GLX_STEREO;
718         if (samples > 1)
719         {
720                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
721                 *attrib++ = 1;
722                 *attrib++ = GLX_SAMPLES_ARB;
723                 *attrib++ = samples;
724         }
725         *attrib++ = None;
726 }
727
728 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
729 {
730         int i;
731         int attrib[32];
732         XSetWindowAttributes attr;
733         XClassHint *clshints;
734         XWMHints *wmhints;
735         XSizeHints *szhints;
736         unsigned long mask;
737         Window root;
738         XVisualInfo *visinfo;
739         int MajorVersion, MinorVersion;
740         const char *drivername;
741
742 #if defined(__APPLE__) && defined(__MACH__)
743         drivername = "/usr/X11R6/lib/libGL.1.dylib";
744 #else
745         drivername = "libGL.so.1";
746 #endif
747 // 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
748 // 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
749 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
750         i = COM_CheckParm("-gl_driver");
751         if (i && i < com_argc - 1)
752                 drivername = com_argv[i + 1];
753         if (!GL_OpenLibrary(drivername))
754         {
755                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
756                 return false;
757         }
758
759         if (!(vidx11_display = XOpenDisplay(NULL)))
760         {
761                 Con_Print("Couldn't open the X display\n");
762                 return false;
763         }
764
765         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
766         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
767
768         vidx11_screen = DefaultScreen(vidx11_display);
769         root = RootWindow(vidx11_display, vidx11_screen);
770
771         // Get video mode list
772         MajorVersion = MinorVersion = 0;
773         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
774                 vidmode_ext = false;
775         else
776         {
777                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
778                 vidmode_ext = true;
779         }
780
781         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
782          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
783          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
784          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
785          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
786          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
787         {
788                 Con_Printf("glX functions not found in %s\n", gl_driver);
789                 return false;
790         }
791
792         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, samples);
793         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
794         if (!visinfo)
795         {
796                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
797                 return false;
798         }
799
800         if (vidmode_ext)
801         {
802                 int best_fit, best_dist, dist, x, y;
803
804                 // Are we going fullscreen?  If so, let's change video mode
805                 if (fullscreen)
806                 {
807                         XF86VidModeModeLine *current_vidmode;
808                         XF86VidModeModeInfo **vidmodes;
809                         int num_vidmodes;
810
811                         // This nice hack comes from the SDL source code
812                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
813                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
814
815                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
816                         best_dist = 9999999;
817                         best_fit = -1;
818
819                         for (i = 0; i < num_vidmodes; i++)
820                         {
821                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
822                                         continue;
823
824                                 x = width - vidmodes[i]->hdisplay;
825                                 y = height - vidmodes[i]->vdisplay;
826                                 dist = (x * x) + (y * y);
827                                 if (dist < best_dist)
828                                 {
829                                         best_dist = dist;
830                                         best_fit = i;
831                                 }
832                         }
833
834                         if (best_fit != -1)
835                         {
836                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
837                                 // to width/height =, so the window will take the full area of
838                                 // the mode chosen
839                                 width = vidmodes[best_fit]->hdisplay;
840                                 height = vidmodes[best_fit]->vdisplay;
841
842                                 // change to the mode
843                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
844                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
845                                 vid_isfullscreen = true;
846
847                                 // Move the viewport to top left
848                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
849                         }
850                         else
851                                 fullscreen = 0;
852
853                         free(vidmodes);
854                 }
855         }
856
857         // LordHavoc: save the visual for use in gamma ramp settings later
858         vidx11_visual = visinfo->visual;
859
860         /* window attributes */
861         attr.background_pixel = 0;
862         attr.border_pixel = 0;
863         // LordHavoc: save the colormap for later, too
864         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
865         attr.event_mask = X_MASK;
866         if (vid_isfullscreen)
867         {
868                 if(vid_isnetwmfullscreen)
869                 {
870                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
871                         attr.backing_store = NotUseful;
872                         attr.save_under = False;
873                 }
874                 else
875                 {
876                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
877                         attr.override_redirect = True;
878                         attr.backing_store = NotUseful;
879                         attr.save_under = False;
880                 }
881         }
882         else
883                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
884
885         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
886
887         wmhints = XAllocWMHints();
888         if(XpmCreatePixmapFromData(vidx11_display, win,
889                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
890                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
891                 wmhints->flags |= IconPixmapHint | IconMaskHint;
892
893         clshints = XAllocClassHint();
894         clshints->res_name = strdup(gamename);
895         clshints->res_class = strdup("DarkPlaces");
896
897         szhints = XAllocSizeHints();
898         if(vid_resizable.integer == 0)
899         {
900                 szhints->min_width = szhints->max_width = width;
901                 szhints->min_height = szhints->max_height = height;
902                 szhints->flags |= PMinSize | PMaxSize;
903         }
904
905         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
906         XFree(clshints);
907         XFree(wmhints);
908         XFree(szhints);
909
910         if(vid_isfullscreen && vid_netwmfullscreen.integer)
911         {
912                 Atom net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
913                 Atom net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
914                 XChangeProperty(vidx11_display, win, net_wm_state_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *) &net_wm_state_fullscreen_atom, 1);
915                 vid_isnetwmfullscreen = true;
916         }
917         else
918                 vid_isnetwmfullscreen = false;
919
920         //XStoreName(vidx11_display, win, gamename);
921         XMapWindow(vidx11_display, win);
922
923         // LordHavoc: making the close button on a window do the right thing
924         // seems to involve this mess, sigh...
925         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
926         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
927
928         if (vid_isfullscreen)
929         {
930                 XMoveWindow(vidx11_display, win, 0, 0);
931                 XRaiseWindow(vidx11_display, win);
932                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
933                 XFlush(vidx11_display);
934                 // Move the viewport to top left
935                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
936         }
937
938         //XSync(vidx11_display, False);
939
940         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
941         if (!ctx)
942         {
943                 Con_Printf ("glXCreateContext failed\n");
944                 return false;
945         }
946
947         if (!qglXMakeCurrent(vidx11_display, win, ctx))
948         {
949                 Con_Printf ("glXMakeCurrent failed\n");
950                 return false;
951         }
952
953         XSync(vidx11_display, False);
954
955         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
956         {
957                 Con_Printf ("glGetString not found in %s\n", gl_driver);
958                 return false;
959         }
960
961         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
962         gl_platform = "GLX";
963         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
964
965         gl_videosyncavailable = false;
966
967 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
968 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
969 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
970         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
971 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
972 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
973 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
974         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
975
976         vid_usingmousegrab = false;
977         vid_usingmouse = false;
978         vid_usinghidecursor = false;
979         vid_usingvsync = false;
980         vid_hidden = false;
981         vid_activewindow = true;
982         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
983 #if !defined(__APPLE__) && !defined(SUNOS)
984         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
985         if (!vid_x11_dgasupported)
986                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
987 #endif
988         GL_Init();
989         return true;
990 }
991
992 void Sys_SendKeyEvents(void)
993 {
994         static qboolean sound_active = true;
995
996         // enable/disable sound on focus gain/loss
997         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
998         {
999                 if (!sound_active)
1000                 {
1001                         S_UnblockSound ();
1002                         sound_active = true;
1003                 }
1004         }
1005         else
1006         {
1007                 if (sound_active)
1008                 {
1009                         S_BlockSound ();
1010                         sound_active = false;
1011                 }
1012         }
1013
1014         HandleEvents();
1015 }
1016
1017 void IN_Move (void)
1018 {
1019 }