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