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