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