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