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