]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_glx.c
implemented support for Windows XInput (using different keys/cvars to allow non-confl...
[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 #include "dpsoftrast.h"
32
33 #include <X11/keysym.h>
34 #include <X11/cursorfont.h>
35 #include <X11/xpm.h>
36
37 #include <X11/extensions/XShm.h>
38 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
39 #include <X11/extensions/xf86dga.h>
40 #endif
41 #include <X11/extensions/xf86vmode.h>
42
43 #include <sys/ipc.h>
44 #include <sys/shm.h>
45 #include <X11/extensions/XShm.h>
46
47 // get the Uchar type
48 #include "utf8lib.h"
49 #include "image.h"
50
51 #include "nexuiz.xpm"
52 #include "darkplaces.xpm"
53
54 // Tell startup code that we have a client
55 int cl_available = true;
56
57 // note: if we used the XRandR extension we could support refresh rates
58 qboolean vid_supportrefreshrate = false;
59
60 //GLX prototypes
61 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
62 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
63 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
64 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
65 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
66 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
67
68 //GLX_ARB_get_proc_address
69 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
70
71 static dllfunction_t getprocaddressfuncs[] =
72 {
73         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
74         {NULL, NULL}
75 };
76
77 //GLX_SGI_swap_control
78 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
79
80 static dllfunction_t swapcontrolfuncs[] =
81 {
82         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
83         {NULL, NULL}
84 };
85
86 static Display *vidx11_display = NULL;
87 static int vidx11_screen;
88 static Window win, root;
89 static GLXContext ctx = NULL;
90 static GC vidx11_gc = NULL;
91 static XImage *vidx11_ximage[2] = { NULL, NULL };
92 static int vidx11_ximage_pos = 0;
93 static XShmSegmentInfo vidx11_shminfo[2];
94 static int vidx11_shmevent = -1;
95 static int vidx11_shmwait = 0; // number of frames outstanding
96
97 Atom wm_delete_window_atom;
98 Atom net_wm_state_atom;
99 Atom net_wm_state_hidden_atom;
100 Atom net_wm_state_fullscreen_atom;
101 Atom net_wm_icon;
102 Atom cardinal;
103
104 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
105 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
106                     PointerMotionMask | ButtonMotionMask)
107 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
108                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
109                 LeaveWindowMask)
110
111
112 static qboolean mouse_avail = true;
113 static qboolean vid_usingmousegrab = false;
114 static qboolean vid_usingmouse = false;
115 static qboolean vid_usinghidecursor = false;
116 static qboolean vid_usingvsync = false;
117 static qboolean vid_usevsync = false;
118 static qboolean vid_x11_hardwaregammasupported = false;
119 static qboolean vid_x11_dgasupported = false;
120 static int vid_x11_gammarampsize = 0;
121
122 #if !defined(__APPLE__) && !defined(SUNOS)
123 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "0", "make use of DGA mouse input"};
124 static qboolean vid_usingdgamouse = false;
125 #endif
126 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"};
127
128 qboolean vidmode_ext = false;
129
130 static int win_x, win_y;
131
132 static XF86VidModeModeInfo init_vidmode, game_vidmode;
133 static qboolean vid_isfullscreen = false;
134 static qboolean vid_isvidmodefullscreen = false;
135 static qboolean vid_isnetwmfullscreen = false;
136 static qboolean vid_isoverrideredirect = false;
137
138 static Visual *vidx11_visual;
139 static Colormap vidx11_colormap;
140
141 /*-----------------------------------------------------------------------*/
142 //
143
144 long keysym2ucs(KeySym keysym);
145 void DP_Xutf8LookupString(XKeyEvent * ev,
146                          Uchar *uch,
147                          KeySym * keysym_return,
148                          Status * status_return)
149 {
150         int rc;
151         KeySym keysym;
152         int codepoint;
153         char buffer[64];
154         int nbytes = sizeof(buffer);
155
156         rc = XLookupString(ev, buffer, nbytes, &keysym, NULL);
157
158         if (rc > 0) {
159                 codepoint = buffer[0] & 0xFF;
160         } else {
161                 codepoint = keysym2ucs(keysym);
162         }
163
164         if (codepoint < 0) {
165                 if (keysym == None) {
166                         *status_return = XLookupNone;
167                 } else {
168                         *status_return = XLookupKeySym;
169                         *keysym_return = keysym;
170                 }
171                 *uch = 0;
172                 return;
173         }
174
175         *uch = codepoint;
176
177         if (keysym != None) {
178                 *keysym_return = keysym;
179                 *status_return = XLookupBoth;
180         } else {
181                 *status_return = XLookupChars;
182         }
183 }
184 static int XLateKey(XKeyEvent *ev, Uchar *ascii)
185 {
186         int key = 0;
187         //char buf[64];
188         KeySym keysym, shifted;
189         Status status;
190
191         keysym = XLookupKeysym (ev, 0);
192         DP_Xutf8LookupString(ev, ascii, &shifted, &status);
193
194         switch(keysym)
195         {
196                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
197                 case XK_Page_Up:         key = K_PGUP; break;
198
199                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
200                 case XK_Page_Down:       key = K_PGDN; break;
201
202                 case XK_KP_Home: key = K_KP_HOME; break;
203                 case XK_Home:    key = K_HOME; break;
204
205                 case XK_KP_End:  key = K_KP_END; break;
206                 case XK_End:     key = K_END; break;
207
208                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
209                 case XK_Left:    key = K_LEFTARROW; break;
210
211                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
212                 case XK_Right:  key = K_RIGHTARROW;             break;
213
214                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
215                 case XK_Down:    key = K_DOWNARROW; break;
216
217                 case XK_KP_Up:   key = K_KP_UPARROW; break;
218                 case XK_Up:              key = K_UPARROW;        break;
219
220                 case XK_Escape: key = K_ESCAPE;         break;
221
222                 case XK_KP_Enter: key = K_KP_ENTER;     break;
223                 case XK_Return: key = K_ENTER;           break;
224
225                 case XK_Tab:            key = K_TAB;                     break;
226
227                 case XK_F1:              key = K_F1;                            break;
228
229                 case XK_F2:              key = K_F2;                            break;
230
231                 case XK_F3:              key = K_F3;                            break;
232
233                 case XK_F4:              key = K_F4;                            break;
234
235                 case XK_F5:              key = K_F5;                            break;
236
237                 case XK_F6:              key = K_F6;                            break;
238
239                 case XK_F7:              key = K_F7;                            break;
240
241                 case XK_F8:              key = K_F8;                            break;
242
243                 case XK_F9:              key = K_F9;                            break;
244
245                 case XK_F10:            key = K_F10;                     break;
246
247                 case XK_F11:            key = K_F11;                     break;
248
249                 case XK_F12:            key = K_F12;                     break;
250
251                 case XK_BackSpace: key = K_BACKSPACE; break;
252
253                 case XK_KP_Delete: key = K_KP_DEL; break;
254                 case XK_Delete: key = K_DEL; break;
255
256                 case XK_Pause:  key = K_PAUSE;           break;
257
258                 case XK_Shift_L:
259                 case XK_Shift_R:        key = K_SHIFT;          break;
260
261                 case XK_Execute:
262                 case XK_Control_L:
263                 case XK_Control_R:      key = K_CTRL;            break;
264
265                 case XK_Alt_L:
266                 case XK_Meta_L:
267                 case XK_ISO_Level3_Shift:
268                 case XK_Alt_R:
269                 case XK_Meta_R: key = K_ALT;                    break;
270
271                 case XK_KP_Begin: key = K_KP_5; break;
272
273                 case XK_Insert:key = K_INS; break;
274                 case XK_KP_Insert: key = K_KP_INS; break;
275
276                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
277                 case XK_KP_Add:  key = K_KP_PLUS; break;
278                 case XK_KP_Subtract: key = K_KP_MINUS; break;
279                 case XK_KP_Divide: key = K_KP_SLASH; break;
280
281                 case XK_section:        key = '~'; break;
282
283                 default:
284                         if (keysym < 32)
285                                 break;
286
287                         if (keysym >= 'A' && keysym <= 'Z')
288                                 key = keysym - 'A' + 'a';
289                         else
290                                 key = keysym;
291
292                         break;
293         }
294
295         return key;
296 }
297
298 static Cursor CreateNullCursor(Display *display, Window root)
299 {
300         Pixmap cursormask;
301         XGCValues xgc;
302         GC gc;
303         XColor dummycolour;
304         Cursor cursor;
305
306         cursormask = XCreatePixmap(display, root, 1, 1, 1);
307         xgc.function = GXclear;
308         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
309         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
310         dummycolour.pixel = 0;
311         dummycolour.red = 0;
312         dummycolour.flags = 04;
313         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
314         XFreePixmap(display,cursormask);
315         XFreeGC(display,gc);
316         return cursor;
317 }
318
319 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
320 {
321         static int originalmouseparms_num;
322         static int originalmouseparms_denom;
323         static int originalmouseparms_threshold;
324         static qboolean restore_spi;
325
326 #if !defined(__APPLE__) && !defined(SUNOS)
327         qboolean usedgamouse;
328 #endif
329
330         if (!vidx11_display || !win)
331                 return;
332
333         if (relative)
334                 fullscreengrab = true;
335
336         if (!mouse_avail)
337                 fullscreengrab = relative = hidecursor = false;
338
339 #if !defined(__APPLE__) && !defined(SUNOS)
340         usedgamouse = relative && vid_dgamouse.integer;
341         if (!vid_x11_dgasupported)
342                 usedgamouse = false;
343         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
344                 VID_SetMouse(false, false, false); // ungrab first!
345 #endif
346
347         if (vid_usingmousegrab != fullscreengrab)
348         {
349                 vid_usingmousegrab = fullscreengrab;
350                 cl_ignoremousemoves = 2;
351                 if (fullscreengrab)
352                 {
353                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
354                         if (vid_grabkeyboard.integer || vid_isoverrideredirect)
355                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
356                 }
357                 else
358                 {
359                         XUngrabPointer(vidx11_display, CurrentTime);
360                         XUngrabKeyboard(vidx11_display, CurrentTime);
361                 }
362         }
363
364         if (relative)
365         {
366                 if (!vid_usingmouse)
367                 {
368                         XWindowAttributes attribs_1;
369                         XSetWindowAttributes attribs_2;
370
371                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
372                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
373                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
374
375 #if !defined(__APPLE__) && !defined(SUNOS)
376                         vid_usingdgamouse = usedgamouse;
377                         if (usedgamouse)
378                         {
379                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
380                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
381                         }
382                         else
383 #endif
384                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
385
386 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
387 #if !defined(__APPLE__) && !defined(SUNOS)
388                         if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
389 #else
390                         if (!COM_CheckParm ("-noforcemparms"))
391 #endif
392                         {
393                                 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
394                                 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
395                                 restore_spi = true;
396                         }
397                         else
398                                 restore_spi = false;
399
400                         cl_ignoremousemoves = 2;
401                         vid_usingmouse = true;
402                 }
403         }
404         else
405         {
406                 if (vid_usingmouse)
407                 {
408 #if !defined(__APPLE__) && !defined(SUNOS)
409                         if (vid_usingdgamouse)
410                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
411                         vid_usingdgamouse = false;
412 #endif
413                         cl_ignoremousemoves = 2;
414
415                         if (restore_spi)
416                                 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
417                         restore_spi = false;
418
419                         vid_usingmouse = false;
420                 }
421         }
422
423         if (vid_usinghidecursor != hidecursor)
424         {
425                 vid_usinghidecursor = hidecursor;
426                 if (hidecursor)
427                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
428                 else
429                         XUndefineCursor(vidx11_display, win);
430         }
431 }
432
433 static keynum_t buttonremap[18] =
434 {
435         K_MOUSE1,
436         K_MOUSE3,
437         K_MOUSE2,
438         K_MWHEELUP,
439         K_MWHEELDOWN,
440         K_MOUSE4,
441         K_MOUSE5,
442         K_MOUSE6,
443         K_MOUSE7,
444         K_MOUSE8,
445         K_MOUSE9,
446         K_MOUSE10,
447         K_MOUSE11,
448         K_MOUSE12,
449         K_MOUSE13,
450         K_MOUSE14,
451         K_MOUSE15,
452         K_MOUSE16,
453 };
454
455 static qboolean BuildXImages(int w, int h)
456 {
457         int i;
458         if(DefaultDepth(vidx11_display, vidx11_screen) != 32 && DefaultDepth(vidx11_display, vidx11_screen) != 24)
459         {
460                 Con_Printf("Sorry, we only support 24bpp and 32bpp modes\n");
461                 VID_Shutdown();
462                 return false;
463         }
464         // match to dpsoftrast's specs
465         if(vidx11_visual->red_mask != 0x00FF0000)
466         {
467                 Con_Printf("Sorry, we only support BGR visuals\n");
468                 VID_Shutdown();
469                 return false;
470         }
471         if(vidx11_visual->green_mask != 0x0000FF00)
472         {
473                 Con_Printf("Sorry, we only support BGR visuals\n");
474                 VID_Shutdown();
475                 return false;
476         }
477         if(vidx11_visual->blue_mask != 0x000000FF)
478         {
479                 Con_Printf("Sorry, we only support BGR visuals\n");
480                 VID_Shutdown();
481                 return false;
482         }
483         if(vidx11_shmevent >= 0)
484         {
485                 for(i = 0; i < 2; ++i)
486                 {
487                         vidx11_shminfo[i].shmid = -1;
488                         vidx11_ximage[i] = XShmCreateImage(vidx11_display, vidx11_visual, DefaultDepth(vidx11_display, vidx11_screen), ZPixmap, NULL, &vidx11_shminfo[i], w, h);
489                         if(!vidx11_ximage[i])
490                         {
491                                 Con_Printf("Failed to get an XImage segment\n");
492                                 VID_Shutdown();
493                                 return false;
494                         }
495                         if(vidx11_ximage[i]->bytes_per_line != w * 4)
496                         {
497                                 Con_Printf("Sorry, we only support linear pixel layout\n");
498                                 VID_Shutdown();
499                                 return false;
500                         }
501                         vidx11_shminfo[i].shmid = shmget(IPC_PRIVATE, vidx11_ximage[i]->bytes_per_line * vidx11_ximage[i]->height, IPC_CREAT|0777);
502                         if(vidx11_shminfo[i].shmid < 0)
503                         {
504                                 Con_Printf("Failed to get a shm segment\n");
505                                 VID_Shutdown();
506                                 return false;
507                         }
508                         vidx11_shminfo[i].shmaddr = vidx11_ximage[i]->data = shmat(vidx11_shminfo[i].shmid, NULL, 0);
509                         if(!vidx11_shminfo[i].shmaddr)
510                         {
511                                 Con_Printf("Failed to get a shm segment addresst\n");
512                                 VID_Shutdown();
513                                 return false;
514                         }
515                         vidx11_shminfo[i].readOnly = True;
516                         XShmAttach(vidx11_display, &vidx11_shminfo[i]);
517                 }
518         }
519         else
520         {
521                 for(i = 0; i < 1; ++i) // we only need one buffer if we don't use Xshm
522                 {
523                         char *p = calloc(4, w * h);
524                         vidx11_shminfo[i].shmid = -1;
525                         vidx11_ximage[i] = XCreateImage(vidx11_display, vidx11_visual, DefaultDepth(vidx11_display, vidx11_screen), ZPixmap, 0, (char*)p, w, h, 8, 0);
526                         if(!vidx11_ximage[i])
527                         {
528                                 Con_Printf("Failed to get an XImage segment\n");
529                                 VID_Shutdown();
530                                 return false;
531                         }
532                         if(vidx11_ximage[i]->bytes_per_line != w * 4)
533                         {
534                                 Con_Printf("Sorry, we only support linear pixel layout\n");
535                                 VID_Shutdown();
536                                 return false;
537                         }
538                 }
539         }
540         return true;
541 }
542 static void DestroyXImages(void)
543 {
544         int i;
545         for(i = 0; i < 2; ++i)
546         {
547                 if(vidx11_shminfo[i].shmid >= 0)
548                 {
549                         XShmDetach(vidx11_display, &vidx11_shminfo[i]);
550                         XDestroyImage(vidx11_ximage[i]);
551                         vidx11_ximage[i] = NULL;
552                         shmdt(vidx11_shminfo[i].shmaddr);
553                         shmctl(vidx11_shminfo[i].shmid, IPC_RMID, 0);
554                         vidx11_shminfo[i].shmid = -1;
555                 }
556                 if(vidx11_ximage[i])
557                         XDestroyImage(vidx11_ximage[i]);
558                 vidx11_ximage[i] = 0;
559         }
560 }
561
562 static int in_mouse_x_save = 0, in_mouse_y_save = 0;
563 static void HandleEvents(void)
564 {
565         XEvent event;
566         int key;
567         Uchar unicode;
568         qboolean dowarp = false;
569
570         if (!vidx11_display)
571                 return;
572
573         in_mouse_x += in_mouse_x_save;
574         in_mouse_y += in_mouse_y_save;
575         in_mouse_x_save = 0;
576         in_mouse_y_save = 0;
577
578         while (XPending(vidx11_display))
579         {
580                 XNextEvent(vidx11_display, &event);
581
582                 switch (event.type)
583                 {
584                 case KeyPress:
585                         // key pressed
586                         key = XLateKey (&event.xkey, &unicode);
587                         Key_Event(key, unicode, true);
588                         break;
589
590                 case KeyRelease:
591                         // key released
592                         key = XLateKey (&event.xkey, &unicode);
593                         Key_Event(key, unicode, false);
594                         break;
595
596                 case MotionNotify:
597                         // mouse moved
598                         if (vid_usingmouse)
599                         {
600 #if !defined(__APPLE__) && !defined(SUNOS)
601                                 if (vid_usingdgamouse)
602                                 {
603                                         in_mouse_x += event.xmotion.x_root;
604                                         in_mouse_y += event.xmotion.y_root;
605                                 }
606                                 else
607 #endif
608                                 {
609                                         if (!event.xmotion.send_event)
610                                         {
611                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
612                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
613                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
614                                                 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)
615                                                         dowarp = true;
616                                         }
617                                 }
618                         }
619                         in_windowmouse_x = event.xmotion.x;
620                         in_windowmouse_y = event.xmotion.y;
621                         break;
622
623                 case ButtonPress:
624                         // mouse button pressed
625                         if (event.xbutton.button <= 18)
626                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
627                         else
628                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
629                         break;
630
631                 case ButtonRelease:
632                         // mouse button released
633                         if (event.xbutton.button <= 18)
634                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
635                         else
636                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
637                         break;
638
639                 case CreateNotify:
640                         // window created
641                         win_x = event.xcreatewindow.x;
642                         win_y = event.xcreatewindow.y;
643                         break;
644
645                 case ConfigureNotify:
646                         // window changed size/location
647                         win_x = event.xconfigure.x;
648                         win_y = event.xconfigure.y;
649                         if((vid_resizable.integer < 2 || vid_isnetwmfullscreen) && (vid.width != event.xconfigure.width || vid.height != event.xconfigure.height))
650                         {
651                                 vid.width = event.xconfigure.width;
652                                 vid.height = event.xconfigure.height;
653                                 if(vid_isnetwmfullscreen)
654                                         Con_Printf("NetWM fullscreen: actually using resolution %dx%d\n", vid.width, vid.height);
655                                 else
656                                         Con_DPrintf("Updating to ConfigureNotify resolution %dx%d\n", vid.width, vid.height);
657
658                                 DPSOFTRAST_Flush();
659
660                                 if(vid.softdepthpixels)
661                                         free(vid.softdepthpixels);
662
663                                 DestroyXImages();
664                                 XSync(vidx11_display, False);
665                                 if(!BuildXImages(vid.width, vid.height))
666                                         return;
667                                 XSync(vidx11_display, False);
668
669                                 vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
670                                 vid.softdepthpixels = (unsigned int *)calloc(4, vid.width * vid.height);
671                         }
672                         break;
673                 case DestroyNotify:
674                         // window has been destroyed
675                         Sys_Quit(0);
676                         break;
677                 case ClientMessage:
678                         // window manager messages
679                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
680                                 Sys_Quit(0);
681                         break;
682                 case MapNotify:
683                         if (vid_isoverrideredirect)
684                                 break;
685                         // window restored
686                         vid_hidden = false;
687                         VID_RestoreSystemGamma();
688
689                         if(vid_isvidmodefullscreen)
690                         {
691                                 // set our video mode
692                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &game_vidmode);
693
694                                 // Move the viewport to top left
695                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
696                         }
697
698                         if(vid_isnetwmfullscreen)
699                         {
700                                 // make sure it's fullscreen
701                                 XEvent event;
702                                 event.type = ClientMessage;
703                                 event.xclient.serial = 0;
704                                 event.xclient.send_event = True;
705                                 event.xclient.message_type = net_wm_state_atom;
706                                 event.xclient.window = win;
707                                 event.xclient.format = 32;
708                                 event.xclient.data.l[0] = 1;
709                                 event.xclient.data.l[1] = net_wm_state_fullscreen_atom;
710                                 event.xclient.data.l[2] = 0;
711                                 event.xclient.data.l[3] = 1;
712                                 event.xclient.data.l[4] = 0;
713                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
714                         }
715
716                         dowarp = true;
717
718                         break;
719                 case UnmapNotify:
720                         if (vid_isoverrideredirect)
721                                 break;
722                         // window iconified/rolledup/whatever
723                         vid_hidden = true;
724                         VID_RestoreSystemGamma();
725
726                         if(vid_isvidmodefullscreen)
727                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
728
729                         break;
730                 case FocusIn:
731                         if (vid_isoverrideredirect)
732                                 break;
733                         // window is now the input focus
734                         vid_activewindow = true;
735                         break;
736                 case FocusOut:
737                         if (vid_isoverrideredirect)
738                                 break;
739
740                         if(vid_isnetwmfullscreen && event.xfocus.mode == NotifyNormal)
741                         {
742                                 // iconify netwm fullscreen window when it loses focus
743                                 // when the user selects it in the taskbar, the window manager will map it again and send MapNotify
744                                 XEvent event;
745                                 event.type = ClientMessage;
746                                 event.xclient.serial = 0;
747                                 event.xclient.send_event = True;
748                                 event.xclient.message_type = net_wm_state_atom;
749                                 event.xclient.window = win;
750                                 event.xclient.format = 32;
751                                 event.xclient.data.l[0] = 1;
752                                 event.xclient.data.l[1] = net_wm_state_hidden_atom;
753                                 event.xclient.data.l[2] = 0;
754                                 event.xclient.data.l[3] = 1;
755                                 event.xclient.data.l[4] = 0;
756                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
757                         }
758
759                         // window is no longer the input focus
760                         vid_activewindow = false;
761                         VID_RestoreSystemGamma();
762
763                         break;
764                 case EnterNotify:
765                         // mouse entered window
766                         break;
767                 case LeaveNotify:
768                         // mouse left window
769                         break;
770                 default:
771                         if(vidx11_shmevent >= 0 && event.type == vidx11_shmevent)
772                                 --vidx11_shmwait;
773                         break;
774                 }
775         }
776
777         if (dowarp)
778         {
779                 /* move the mouse to the window center again */
780                 // we'll catch the warp motion by its send_event flag, updating the
781                 // stored mouse position without adding any delta motion
782                 XEvent event;
783                 event.type = MotionNotify;
784                 event.xmotion.display = vidx11_display;
785                 event.xmotion.window = win;
786                 event.xmotion.x = vid.width / 2;
787                 event.xmotion.y = vid.height / 2;
788                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
789                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
790         }
791 }
792
793 static void *prjobj = NULL;
794
795 static void GL_CloseLibrary(void)
796 {
797         if (prjobj)
798                 dlclose(prjobj);
799         prjobj = NULL;
800         gl_driver[0] = 0;
801         qglXGetProcAddressARB = NULL;
802         gl_extensions = "";
803         gl_platform = "";
804         gl_platformextensions = "";
805 }
806
807 static int GL_OpenLibrary(const char *name)
808 {
809         Con_Printf("Loading OpenGL driver %s\n", name);
810         GL_CloseLibrary();
811         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
812         {
813                 Con_Printf("Unable to open symbol list for %s\n", name);
814                 return false;
815         }
816         strlcpy(gl_driver, name, sizeof(gl_driver));
817         return true;
818 }
819
820 void *GL_GetProcAddress(const char *name)
821 {
822         void *p = NULL;
823         if (qglXGetProcAddressARB != NULL)
824                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
825         if (p == NULL)
826                 p = (void *) dlsym(prjobj, name);
827         return p;
828 }
829
830 void VID_Shutdown(void)
831 {
832         if (!vidx11_display)
833                 return;
834
835         VID_EnableJoystick(false);
836         VID_SetMouse(false, false, false);
837         VID_RestoreSystemGamma();
838
839         // FIXME: glXDestroyContext here?
840         if (vid_isvidmodefullscreen)
841                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
842
843         if(vidx11_gc)
844                 XFreeGC(vidx11_display, vidx11_gc);
845         vidx11_gc = NULL;
846
847         DestroyXImages();
848         vidx11_shmevent = -1;
849         vid.softpixels = NULL;
850
851         if (vid.softdepthpixels)
852                 free(vid.softdepthpixels);
853         vid.softdepthpixels = NULL;
854
855         if (win)
856                 XDestroyWindow(vidx11_display, win);
857         XCloseDisplay(vidx11_display);
858
859         vid_hidden = true;
860         vid_isfullscreen = false;
861         vid_isnetwmfullscreen = false;
862         vid_isvidmodefullscreen = false;
863         vid_isoverrideredirect = false;
864         vidx11_display = NULL;
865         win = 0;
866         ctx = NULL;
867
868         GL_CloseLibrary();
869         Key_ClearStates ();
870 }
871
872 void signal_handler(int sig)
873 {
874         Con_Printf("Received signal %d, exiting...\n", sig);
875         VID_RestoreSystemGamma();
876         Sys_Quit(1);
877 }
878
879 void InitSig(void)
880 {
881         signal(SIGHUP, signal_handler);
882         signal(SIGINT, signal_handler);
883         signal(SIGQUIT, signal_handler);
884         signal(SIGILL, signal_handler);
885         signal(SIGTRAP, signal_handler);
886         signal(SIGIOT, signal_handler);
887         signal(SIGBUS, signal_handler);
888         signal(SIGFPE, signal_handler);
889         signal(SIGSEGV, signal_handler);
890         signal(SIGTERM, signal_handler);
891 }
892
893 void VID_Finish (void)
894 {
895         vid_usevsync = vid_vsync.integer && !cls.timedemo && qglXSwapIntervalSGI;
896         switch(vid.renderpath)
897         {
898                 case RENDERPATH_SOFT:
899                         if(vidx11_shmevent >= 0) {
900                                 vidx11_ximage_pos = !vidx11_ximage_pos;
901                                 vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
902                                 DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
903
904                                 // save mouse motion so we can deal with it later
905                                 in_mouse_x = 0;
906                                 in_mouse_y = 0;
907                                 while(vidx11_shmwait)
908                                         HandleEvents();
909                                 in_mouse_x_save += in_mouse_x;
910                                 in_mouse_y_save += in_mouse_y;
911                                 in_mouse_x = 0;
912                                 in_mouse_y = 0;
913
914                                 ++vidx11_shmwait;
915                                 XShmPutImage(vidx11_display, win, vidx11_gc, vidx11_ximage[!vidx11_ximage_pos], 0, 0, 0, 0, vid.width, vid.height, True);
916                         } else {
917                                 // no buffer switching here, we just flush the renderer
918                                 DPSOFTRAST_Finish();
919                                 XPutImage(vidx11_display, win, vidx11_gc, vidx11_ximage[vidx11_ximage_pos], 0, 0, 0, 0, vid.width, vid.height);
920                         }
921                         break;
922
923                 case RENDERPATH_GL11:
924                 case RENDERPATH_GL13:
925                 case RENDERPATH_GL20:
926                 case RENDERPATH_GLES1:
927                 case RENDERPATH_GLES2:
928                         if (vid_usingvsync != vid_usevsync)
929                         {
930                                 vid_usingvsync = vid_usevsync;
931                                 if (qglXSwapIntervalSGI (vid_usevsync))
932                                         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");
933                         }
934
935                         if (!vid_hidden)
936                         {
937                                 CHECKGLERROR
938                                 if (r_speeds.integer == 2 || gl_finish.integer)
939                                         GL_Finish();
940                                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
941                         }
942                         break;
943
944                 case RENDERPATH_D3D9:
945                 case RENDERPATH_D3D10:
946                 case RENDERPATH_D3D11:
947                         break;
948         }
949
950         if (vid_x11_hardwaregammasupported)
951                 VID_UpdateGamma(false, vid_x11_gammarampsize);
952 }
953
954 int VID_SetGamma(unsigned short *ramps, int rampsize)
955 {
956         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
957 }
958
959 int VID_GetGamma(unsigned short *ramps, int rampsize)
960 {
961         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
962 }
963
964 void VID_Init(void)
965 {
966 #if !defined(__APPLE__) && !defined(SUNOS)
967         Cvar_RegisterVariable (&vid_dgamouse);
968 #endif
969         Cvar_RegisterVariable (&vid_netwmfullscreen);
970         InitSig(); // trap evil signals
971 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
972         if (COM_CheckParm ("-nomouse"))
973                 mouse_avail = false;
974         vidx11_shminfo[0].shmid = -1;
975         vidx11_shminfo[1].shmid = -1;
976 }
977
978 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
979 {
980         *attrib++ = GLX_RGBA;
981         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
982         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
983         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
984         *attrib++ = GLX_DOUBLEBUFFER;
985         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
986         // if stencil is enabled, ask for alpha too
987         if (stencil)
988         {
989                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
990                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
991         }
992         if (stereobuffer)
993                 *attrib++ = GLX_STEREO;
994         if (samples > 1)
995         {
996                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
997                 *attrib++ = 1;
998                 *attrib++ = GLX_SAMPLES_ARB;
999                 *attrib++ = samples;
1000         }
1001         *attrib++ = None;
1002 }
1003
1004 qboolean VID_InitModeSoft(viddef_mode_t *mode)
1005 {
1006         int i, j;
1007         XSetWindowAttributes attr;
1008         XClassHint *clshints;
1009         XWMHints *wmhints;
1010         XSizeHints *szhints;
1011         unsigned long mask;
1012         int MajorVersion, MinorVersion;
1013         char *xpm;
1014         char **idata;
1015         unsigned char *data;
1016         XGCValues gcval;
1017         const char *dpyname;
1018
1019         vid_isfullscreen = false;
1020         vid_isnetwmfullscreen = false;
1021         vid_isvidmodefullscreen = false;
1022         vid_isoverrideredirect = false;
1023
1024         if (!(vidx11_display = XOpenDisplay(NULL)))
1025         {
1026                 Con_Print("Couldn't open the X display\n");
1027                 return false;
1028         }
1029         dpyname = XDisplayName(NULL);
1030
1031         // LordHavoc: making the close button on a window do the right thing
1032         // seems to involve this mess, sigh...
1033         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
1034         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
1035         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
1036         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
1037         net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
1038         cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
1039
1040         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
1041         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
1042
1043         vidx11_screen = DefaultScreen(vidx11_display);
1044         root = RootWindow(vidx11_display, vidx11_screen);
1045
1046         // Get video mode list
1047         MajorVersion = MinorVersion = 0;
1048         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
1049                 vidmode_ext = false;
1050         else
1051         {
1052                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
1053                 vidmode_ext = true;
1054         }
1055
1056         if (mode->fullscreen)
1057         {
1058                 if(vid_netwmfullscreen.integer)
1059                 {
1060                         // TODO detect WM support
1061                         vid_isnetwmfullscreen = true;
1062                         vid_isfullscreen = true;
1063                         // width and height will be filled in later
1064                         Con_DPrintf("Using NetWM fullscreen mode\n");
1065                 }
1066
1067                 if(!vid_isfullscreen && vidmode_ext)
1068                 {
1069                         int best_fit, best_dist, dist, x, y;
1070
1071                         // Are we going fullscreen?  If so, let's change video mode
1072                         XF86VidModeModeLine *current_vidmode;
1073                         XF86VidModeModeInfo **vidmodes;
1074                         int num_vidmodes;
1075
1076                         // This nice hack comes from the SDL source code
1077                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
1078                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
1079
1080                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1081                         best_dist = 0;
1082                         best_fit = -1;
1083
1084                         for (i = 0; i < num_vidmodes; i++)
1085                         {
1086                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
1087                                         continue;
1088
1089                                 x = mode->width - vidmodes[i]->hdisplay;
1090                                 y = mode->height - vidmodes[i]->vdisplay;
1091                                 dist = (x * x) + (y * y);
1092                                 if (best_fit == -1 || dist < best_dist)
1093                                 {
1094                                         best_dist = dist;
1095                                         best_fit = i;
1096                                 }
1097                         }
1098
1099                         if (best_fit != -1)
1100                         {
1101                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
1102                                 // to width/height =, so the window will take the full area of
1103                                 // the mode chosen
1104                                 mode->width = vidmodes[best_fit]->hdisplay;
1105                                 mode->height = vidmodes[best_fit]->vdisplay;
1106
1107                                 // change to the mode
1108                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
1109                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
1110                                 vid_isvidmodefullscreen = true;
1111                                 vid_isfullscreen = true;
1112
1113                                 // Move the viewport to top left
1114                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1115                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
1116                         }
1117
1118                         free(vidmodes);
1119                 }
1120
1121                 if(!vid_isfullscreen)
1122                 {
1123                         // sorry, no FS available
1124                         // use the full desktop resolution
1125                         vid_isfullscreen = true;
1126                         // width and height will be filled in later
1127                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
1128                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
1129                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
1130                 }
1131         }
1132
1133         // LordHavoc: save the visual for use in gamma ramp settings later
1134         vidx11_visual = DefaultVisual(vidx11_display, vidx11_screen);
1135
1136         /* window attributes */
1137         attr.background_pixel = 0;
1138         attr.border_pixel = 0;
1139         // LordHavoc: save the colormap for later, too
1140         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, vidx11_visual, AllocNone);
1141         attr.event_mask = X_MASK;
1142
1143         if (mode->fullscreen)
1144         {
1145                 if(vid_isnetwmfullscreen)
1146                 {
1147                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
1148                         attr.backing_store = NotUseful;
1149                         attr.save_under = False;
1150                 }
1151                 else
1152                 {
1153                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
1154                         attr.override_redirect = True;
1155                         attr.backing_store = NotUseful;
1156                         attr.save_under = False;
1157                         vid_isoverrideredirect = true; // so it knows to grab
1158                 }
1159         }
1160         else
1161         {
1162                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1163         }
1164
1165         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, CopyFromParent, InputOutput, vidx11_visual, mask, &attr);
1166
1167         data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1168         if(data)
1169         {
1170                 // use _NET_WM_ICON too
1171                 static long netwm_icon[MAX_NETWM_ICON];
1172                 int pos = 0;
1173                 int i = 1;
1174
1175                 while(data)
1176                 {
1177                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1178                         {
1179                                 netwm_icon[pos++] = image_width;
1180                                 netwm_icon[pos++] = image_height;
1181                                 for(i = 0; i < image_height; ++i)
1182                                         for(j = 0; j < image_width; ++j)
1183                                                 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1184                         }
1185                         else
1186                         {
1187                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1188                         }
1189                         ++i;
1190                         Mem_Free(data);
1191                         data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1192                 }
1193                 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1194         }
1195
1196         // fallthrough for old window managers
1197         xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1198         idata = NULL;
1199         if(xpm)
1200                 idata = XPM_DecodeString(xpm);
1201         if(!idata)
1202                 idata = ENGINE_ICON;
1203
1204         wmhints = XAllocWMHints();
1205         if(XpmCreatePixmapFromData(vidx11_display, win,
1206                 idata,
1207                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1208                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1209
1210         if(xpm)
1211                 Mem_Free(xpm);
1212
1213         clshints = XAllocClassHint();
1214         clshints->res_name = strdup(gamename);
1215         clshints->res_class = strdup("DarkPlaces");
1216
1217         szhints = XAllocSizeHints();
1218         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1219         {
1220                 szhints->min_width = szhints->max_width = mode->width;
1221                 szhints->min_height = szhints->max_height = mode->height;
1222                 szhints->flags |= PMinSize | PMaxSize;
1223         }
1224
1225         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1226         // strdup() allocates using malloc(), should be freed with free()
1227         free(clshints->res_name);
1228         free(clshints->res_class);
1229         XFree(clshints);
1230         XFree(wmhints);
1231         XFree(szhints);
1232
1233         //XStoreName(vidx11_display, win, gamename);
1234         XMapWindow(vidx11_display, win);
1235
1236         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1237
1238         if (vid_isoverrideredirect)
1239         {
1240                 XMoveWindow(vidx11_display, win, 0, 0);
1241                 XRaiseWindow(vidx11_display, win);
1242                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1243                 XFlush(vidx11_display);
1244         }
1245
1246         if(vid_isvidmodefullscreen)
1247         {
1248                 // Move the viewport to top left
1249                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1250         }
1251
1252         //XSync(vidx11_display, False);
1253
1254         // COMMANDLINEOPTION: Unix GLX: -noshm disables XShm extensioon
1255         if(dpyname && dpyname[0] == ':' && dpyname[1] && (dpyname[2] < '0' || dpyname[2] > '9') && !COM_CheckParm("-noshm") && XShmQueryExtension(vidx11_display))
1256         {
1257                 Con_Printf("Using XShm\n");
1258                 vidx11_shmevent = XShmGetEventBase(vidx11_display) + ShmCompletion;
1259         }
1260         else
1261         {
1262                 Con_Printf("Not using XShm\n");
1263                 vidx11_shmevent = -1;
1264         }
1265         BuildXImages(mode->width, mode->height);
1266
1267         vidx11_ximage_pos = 0;
1268         vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
1269         vidx11_shmwait = 0;
1270         vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1271
1272         memset(&gcval, 0, sizeof(gcval));
1273         vidx11_gc = XCreateGC(vidx11_display, win, 0, &gcval);
1274
1275         if (DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, vid_soft_interlace.integer, (unsigned int *)vid.softpixels, (unsigned int *)vid.softdepthpixels) < 0)
1276         {
1277                 Con_Printf("Failed to initialize software rasterizer\n");
1278                 VID_Shutdown();
1279                 return false;
1280         }
1281
1282         XSync(vidx11_display, False);
1283
1284         vid_usingmousegrab = false;
1285         vid_usingmouse = false;
1286         vid_usinghidecursor = false;
1287         vid_usingvsync = false;
1288         vid_hidden = false;
1289         vid_activewindow = true;
1290         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1291 #if !defined(__APPLE__) && !defined(SUNOS)
1292         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1293         if (!vid_x11_dgasupported)
1294                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1295 #endif
1296
1297         VID_Soft_SharedSetup();
1298
1299         return true;
1300 }
1301 qboolean VID_InitModeGL(viddef_mode_t *mode)
1302 {
1303         int i, j;
1304         int attrib[32];
1305         XSetWindowAttributes attr;
1306         XClassHint *clshints;
1307         XWMHints *wmhints;
1308         XSizeHints *szhints;
1309         unsigned long mask;
1310         XVisualInfo *visinfo;
1311         int MajorVersion, MinorVersion;
1312         const char *drivername;
1313         char *xpm;
1314         char **idata;
1315         unsigned char *data;
1316
1317         vid_isfullscreen = false;
1318         vid_isnetwmfullscreen = false;
1319         vid_isvidmodefullscreen = false;
1320         vid_isoverrideredirect = false;
1321
1322 #if defined(__APPLE__) && defined(__MACH__)
1323         drivername = "/usr/X11R6/lib/libGL.1.dylib";
1324 #else
1325         drivername = "libGL.so.1";
1326 #endif
1327 // 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
1328 // 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
1329 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
1330         i = COM_CheckParm("-gl_driver");
1331         if (i && i < com_argc - 1)
1332                 drivername = com_argv[i + 1];
1333         if (!GL_OpenLibrary(drivername))
1334         {
1335                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
1336                 return false;
1337         }
1338
1339         if (!(vidx11_display = XOpenDisplay(NULL)))
1340         {
1341                 Con_Print("Couldn't open the X display\n");
1342                 return false;
1343         }
1344
1345         // LordHavoc: making the close button on a window do the right thing
1346         // seems to involve this mess, sigh...
1347         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
1348         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
1349         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
1350         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
1351         net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
1352         cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
1353
1354         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
1355         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
1356
1357         vidx11_screen = DefaultScreen(vidx11_display);
1358         root = RootWindow(vidx11_display, vidx11_screen);
1359
1360         // Get video mode list
1361         MajorVersion = MinorVersion = 0;
1362         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
1363                 vidmode_ext = false;
1364         else
1365         {
1366                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
1367                 vidmode_ext = true;
1368         }
1369
1370         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
1371          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
1372          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
1373          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
1374          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
1375          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
1376         {
1377                 Con_Printf("glX functions not found in %s\n", gl_driver);
1378                 return false;
1379         }
1380
1381         VID_BuildGLXAttrib(attrib, mode->bitsperpixel == 32, mode->stereobuffer, mode->samples);
1382         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
1383         if (!visinfo)
1384         {
1385                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
1386                 return false;
1387         }
1388
1389         if (mode->fullscreen)
1390         {
1391                 if(vid_netwmfullscreen.integer)
1392                 {
1393                         // TODO detect WM support
1394                         vid_isnetwmfullscreen = true;
1395                         vid_isfullscreen = true;
1396                         // width and height will be filled in later
1397                         Con_DPrintf("Using NetWM fullscreen mode\n");
1398                 }
1399
1400                 if(!vid_isfullscreen && vidmode_ext)
1401                 {
1402                         int best_fit, best_dist, dist, x, y;
1403
1404                         // Are we going fullscreen?  If so, let's change video mode
1405                         XF86VidModeModeLine *current_vidmode;
1406                         XF86VidModeModeInfo **vidmodes;
1407                         int num_vidmodes;
1408
1409                         // This nice hack comes from the SDL source code
1410                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
1411                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
1412
1413                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1414                         best_dist = 0;
1415                         best_fit = -1;
1416
1417                         for (i = 0; i < num_vidmodes; i++)
1418                         {
1419                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
1420                                         continue;
1421
1422                                 x = mode->width - vidmodes[i]->hdisplay;
1423                                 y = mode->height - vidmodes[i]->vdisplay;
1424                                 dist = (x * x) + (y * y);
1425                                 if (best_fit == -1 || dist < best_dist)
1426                                 {
1427                                         best_dist = dist;
1428                                         best_fit = i;
1429                                 }
1430                         }
1431
1432                         if (best_fit != -1)
1433                         {
1434                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
1435                                 // to width/height =, so the window will take the full area of
1436                                 // the mode chosen
1437                                 mode->width = vidmodes[best_fit]->hdisplay;
1438                                 mode->height = vidmodes[best_fit]->vdisplay;
1439
1440                                 // change to the mode
1441                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
1442                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
1443                                 vid_isvidmodefullscreen = true;
1444                                 vid_isfullscreen = true;
1445
1446                                 // Move the viewport to top left
1447                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1448                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
1449                         }
1450
1451                         free(vidmodes);
1452                 }
1453
1454                 if(!vid_isfullscreen)
1455                 {
1456                         // sorry, no FS available
1457                         // use the full desktop resolution
1458                         vid_isfullscreen = true;
1459                         // width and height will be filled in later
1460                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
1461                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
1462                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
1463                 }
1464         }
1465
1466         // LordHavoc: save the visual for use in gamma ramp settings later
1467         vidx11_visual = visinfo->visual;
1468
1469         /* window attributes */
1470         attr.background_pixel = 0;
1471         attr.border_pixel = 0;
1472         // LordHavoc: save the colormap for later, too
1473         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
1474         attr.event_mask = X_MASK;
1475
1476         if (mode->fullscreen)
1477         {
1478                 if(vid_isnetwmfullscreen)
1479                 {
1480                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
1481                         attr.backing_store = NotUseful;
1482                         attr.save_under = False;
1483                 }
1484                 else
1485                 {
1486                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
1487                         attr.override_redirect = True;
1488                         attr.backing_store = NotUseful;
1489                         attr.save_under = False;
1490                         vid_isoverrideredirect = true; // so it knows to grab
1491                 }
1492         }
1493         else
1494         {
1495                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1496         }
1497
1498         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
1499
1500         data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1501         if(data)
1502         {
1503                 // use _NET_WM_ICON too
1504                 static long netwm_icon[MAX_NETWM_ICON];
1505                 int pos = 0;
1506                 int i = 1;
1507
1508                 while(data)
1509                 {
1510                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1511                         {
1512                                 netwm_icon[pos++] = image_width;
1513                                 netwm_icon[pos++] = image_height;
1514                                 for(i = 0; i < image_height; ++i)
1515                                         for(j = 0; j < image_width; ++j)
1516                                                 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1517                         }
1518                         else
1519                         {
1520                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1521                         }
1522                         ++i;
1523                         Mem_Free(data);
1524                         data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1525                 }
1526                 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1527         }
1528
1529         // fallthrough for old window managers
1530         xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1531         idata = NULL;
1532         if(xpm)
1533                 idata = XPM_DecodeString(xpm);
1534         if(!idata)
1535                 idata = ENGINE_ICON;
1536
1537         wmhints = XAllocWMHints();
1538         if(XpmCreatePixmapFromData(vidx11_display, win,
1539                 idata,
1540                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1541                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1542
1543         if(xpm)
1544                 Mem_Free(xpm);
1545
1546         clshints = XAllocClassHint();
1547         clshints->res_name = strdup(gamename);
1548         clshints->res_class = strdup("DarkPlaces");
1549
1550         szhints = XAllocSizeHints();
1551         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1552         {
1553                 szhints->min_width = szhints->max_width = mode->width;
1554                 szhints->min_height = szhints->max_height = mode->height;
1555                 szhints->flags |= PMinSize | PMaxSize;
1556         }
1557
1558         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1559         // strdup() allocates using malloc(), should be freed with free()
1560         free(clshints->res_name);
1561         free(clshints->res_class);
1562         XFree(clshints);
1563         XFree(wmhints);
1564         XFree(szhints);
1565
1566         //XStoreName(vidx11_display, win, gamename);
1567         XMapWindow(vidx11_display, win);
1568
1569         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1570
1571         if (vid_isoverrideredirect)
1572         {
1573                 XMoveWindow(vidx11_display, win, 0, 0);
1574                 XRaiseWindow(vidx11_display, win);
1575                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1576                 XFlush(vidx11_display);
1577         }
1578
1579         if(vid_isvidmodefullscreen)
1580         {
1581                 // Move the viewport to top left
1582                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1583         }
1584
1585         //XSync(vidx11_display, False);
1586
1587         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
1588         XFree(visinfo); // glXChooseVisual man page says to use XFree to free visinfo
1589         if (!ctx)
1590         {
1591                 Con_Printf ("glXCreateContext failed\n");
1592                 return false;
1593         }
1594
1595         if (!qglXMakeCurrent(vidx11_display, win, ctx))
1596         {
1597                 Con_Printf ("glXMakeCurrent failed\n");
1598                 return false;
1599         }
1600
1601         XSync(vidx11_display, False);
1602
1603         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1604         {
1605                 Con_Printf ("glGetString not found in %s\n", gl_driver);
1606                 return false;
1607         }
1608
1609         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1610         gl_platform = "GLX";
1611         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
1612
1613 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1614 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1615 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1616         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
1617 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
1618 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
1619 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
1620         GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
1621
1622         vid_usingmousegrab = false;
1623         vid_usingmouse = false;
1624         vid_usinghidecursor = false;
1625         vid_usingvsync = false;
1626         vid_hidden = false;
1627         vid_activewindow = true;
1628         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1629 #if !defined(__APPLE__) && !defined(SUNOS)
1630         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1631         if (!vid_x11_dgasupported)
1632                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1633 #endif
1634
1635         GL_Init();
1636         return true;
1637 }
1638
1639 qboolean VID_InitMode(viddef_mode_t *mode)
1640 {
1641 #ifdef SSE_POSSIBLE
1642         if (vid_soft.integer)
1643                 return VID_InitModeSoft(mode);
1644         else
1645 #endif
1646                 return VID_InitModeGL(mode);
1647 }
1648
1649 void Sys_SendKeyEvents(void)
1650 {
1651         static qboolean sound_active = true;
1652
1653         // enable/disable sound on focus gain/loss
1654         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1655         {
1656                 if (!sound_active)
1657                 {
1658                         S_UnblockSound ();
1659                         sound_active = true;
1660                 }
1661         }
1662         else
1663         {
1664                 if (sound_active)
1665                 {
1666                         S_BlockSound ();
1667                         sound_active = false;
1668                 }
1669         }
1670
1671         HandleEvents();
1672 }
1673
1674 void VID_BuildJoyState(vid_joystate_t *joystate)
1675 {
1676         VID_Shared_BuildJoyState_Begin(joystate);
1677         VID_Shared_BuildJoyState_Finish(joystate);
1678 }
1679
1680 void VID_EnableJoystick(qboolean enable)
1681 {
1682         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1683         qboolean success = false;
1684         int sharedcount = 0;
1685         sharedcount = VID_Shared_SetJoystick(index);
1686         if (index >= 0 && index < sharedcount)
1687                 success = true;
1688
1689         // update cvar containing count of XInput joysticks
1690         if (joy_detected.integer != sharedcount)
1691                 Cvar_SetValueQuick(&joy_detected, sharedcount);
1692
1693         Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1694 }
1695
1696 void IN_Move (void)
1697 {
1698         vid_joystate_t joystate;
1699         VID_EnableJoystick(true);
1700         VID_BuildJoyState(&joystate);
1701         VID_ApplyJoyState(&joystate);
1702 }
1703
1704 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1705 {
1706         if(vidmode_ext)
1707         {
1708                 int i, bpp;
1709                 size_t k;
1710                 XF86VidModeModeInfo **vidmodes;
1711                 int num_vidmodes;
1712
1713                 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1714                 k = 0;
1715                 for (i = 0; i < num_vidmodes; i++)
1716                 {
1717                         if(k >= maxcount)
1718                                 break;
1719                         // we don't get bpp info, so let's just assume all of 8, 15, 16, 24, 32 work
1720                         for(bpp = 8; bpp <= 32; bpp = ((bpp == 8) ? 15 : (bpp & 0xF8) + 8))
1721                         {
1722                                 if(k >= maxcount)
1723                                         break;
1724                                 modes[k].width = vidmodes[i]->hdisplay;
1725                                 modes[k].height = vidmodes[i]->vdisplay;
1726                                 modes[k].bpp = 8;
1727                                 if(vidmodes[i]->dotclock && vidmodes[i]->htotal && vidmodes[i]->vtotal)
1728                                         modes[k].refreshrate = vidmodes[i]->dotclock / vidmodes[i]->htotal / vidmodes[i]->vtotal;
1729                                 else
1730                                         modes[k].refreshrate = 60;
1731                                 modes[k].pixelheight_num = 1;
1732                                 modes[k].pixelheight_denom = 1; // xvidmode does not provide this
1733                                 ++k;
1734                         }
1735                 }
1736                 // manpage of XF86VidModeGetAllModeLines says it should be freed by the caller
1737                 XFree(vidmodes);
1738                 return k;
1739         }
1740         return 0; // FIXME implement this
1741 }