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