]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_glx.c
add code to vid_glx to turn off mouse acceleration; also support vid_wgl's option...
[divverent/darkplaces.git] / vid_glx.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20 #include <signal.h>
21
22 #include <dlfcn.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <X11/XKBlib.h> // TODO possibly ifdef this out on non-supporting systems... Solaris (as always)?
27 #include <GL/glx.h>
28
29 #include "quakedef.h"
30
31 #include <X11/keysym.h>
32 #include <X11/cursorfont.h>
33 #include <X11/xpm.h>
34
35 #include <X11/extensions/XShm.h>
36 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
37 #include <X11/extensions/xf86dga.h>
38 #endif
39 #include <X11/extensions/xf86vmode.h>
40
41 #include "nexuiz.xpm"
42 #include "darkplaces.xpm"
43
44 // Tell startup code that we have a client
45 int cl_available = true;
46
47 // note: if we used the XRandR extension we could support refresh rates
48 qboolean vid_supportrefreshrate = false;
49
50 //GLX prototypes
51 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
52 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
53 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
54 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
55 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
56 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
57
58 //GLX_ARB_get_proc_address
59 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
60
61 static dllfunction_t getprocaddressfuncs[] =
62 {
63         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
64         {NULL, NULL}
65 };
66
67 //GLX_SGI_swap_control
68 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
69
70 static dllfunction_t swapcontrolfuncs[] =
71 {
72         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
73         {NULL, NULL}
74 };
75
76 static Display *vidx11_display = NULL;
77 static int vidx11_screen;
78 static Window win;
79 static GLXContext ctx = NULL;
80
81 Atom wm_delete_window_atom;
82
83 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
84 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
85                     PointerMotionMask | ButtonMotionMask)
86 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
87                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
88                 LeaveWindowMask)
89
90
91 static qboolean mouse_avail = true;
92 static qboolean vid_usingmousegrab = false;
93 static qboolean vid_usingmouse = false;
94 static qboolean vid_usinghidecursor = false;
95 static qboolean vid_usingvsync = false;
96 static qboolean vid_usevsync = false;
97 static qboolean vid_x11_hardwaregammasupported = false;
98 static qboolean vid_x11_dgasupported = false;
99 static int vid_x11_gammarampsize = 0;
100
101 #if !defined(__APPLE__) && !defined(SUNOS)
102 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "1", "make use of DGA mouse input"};
103 static qboolean vid_usingdgamouse = false;
104 #endif
105
106 qboolean vidmode_ext = false;
107
108 static int win_x, win_y;
109
110 static XF86VidModeModeInfo init_vidmode;
111 static qboolean vid_isfullscreen = false;
112
113 static Visual *vidx11_visual;
114 static Colormap vidx11_colormap;
115
116 /*-----------------------------------------------------------------------*/
117
118 static int XLateKey(XKeyEvent *ev, char *ascii)
119 {
120         int key = 0;
121         char buf[64];
122         KeySym keysym, shifted;
123
124         keysym = XLookupKeysym (ev, 0);
125         XLookupString(ev, buf, sizeof buf, &shifted, 0);
126         *ascii = buf[0];
127
128         switch(keysym)
129         {
130                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
131                 case XK_Page_Up:         key = K_PGUP; break;
132
133                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
134                 case XK_Page_Down:       key = K_PGDN; break;
135
136                 case XK_KP_Home: key = K_KP_HOME; break;
137                 case XK_Home:    key = K_HOME; break;
138
139                 case XK_KP_End:  key = K_KP_END; break;
140                 case XK_End:     key = K_END; break;
141
142                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
143                 case XK_Left:    key = K_LEFTARROW; break;
144
145                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
146                 case XK_Right:  key = K_RIGHTARROW;             break;
147
148                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
149                 case XK_Down:    key = K_DOWNARROW; break;
150
151                 case XK_KP_Up:   key = K_KP_UPARROW; break;
152                 case XK_Up:              key = K_UPARROW;        break;
153
154                 case XK_Escape: key = K_ESCAPE;         break;
155
156                 case XK_KP_Enter: key = K_KP_ENTER;     break;
157                 case XK_Return: key = K_ENTER;           break;
158
159                 case XK_Tab:            key = K_TAB;                     break;
160
161                 case XK_F1:              key = K_F1;                            break;
162
163                 case XK_F2:              key = K_F2;                            break;
164
165                 case XK_F3:              key = K_F3;                            break;
166
167                 case XK_F4:              key = K_F4;                            break;
168
169                 case XK_F5:              key = K_F5;                            break;
170
171                 case XK_F6:              key = K_F6;                            break;
172
173                 case XK_F7:              key = K_F7;                            break;
174
175                 case XK_F8:              key = K_F8;                            break;
176
177                 case XK_F9:              key = K_F9;                            break;
178
179                 case XK_F10:            key = K_F10;                     break;
180
181                 case XK_F11:            key = K_F11;                     break;
182
183                 case XK_F12:            key = K_F12;                     break;
184
185                 case XK_BackSpace: key = K_BACKSPACE; break;
186
187                 case XK_KP_Delete: key = K_KP_DEL; break;
188                 case XK_Delete: key = K_DEL; break;
189
190                 case XK_Pause:  key = K_PAUSE;           break;
191
192                 case XK_Shift_L:
193                 case XK_Shift_R:        key = K_SHIFT;          break;
194
195                 case XK_Execute:
196                 case XK_Control_L:
197                 case XK_Control_R:      key = K_CTRL;            break;
198
199                 case XK_Alt_L:
200                 case XK_Meta_L:
201                 case XK_ISO_Level3_Shift:
202                 case XK_Alt_R:
203                 case XK_Meta_R: key = K_ALT;                    break;
204
205                 case XK_KP_Begin: key = K_KP_5; break;
206
207                 case XK_Insert:key = K_INS; break;
208                 case XK_KP_Insert: key = K_KP_INS; break;
209
210                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
211                 case XK_KP_Add:  key = K_KP_PLUS; break;
212                 case XK_KP_Subtract: key = K_KP_MINUS; break;
213                 case XK_KP_Divide: key = K_KP_SLASH; break;
214
215                 case XK_section:        key = '~'; break;
216
217                 default:
218                         if (keysym < 32)
219                                 break;
220
221                         if (keysym >= 'A' && keysym <= 'Z')
222                                 key = keysym - 'A' + 'a';
223                         else
224                                 key = keysym;
225
226                         break;
227         }
228
229         return key;
230 }
231
232 static Cursor CreateNullCursor(Display *display, Window root)
233 {
234         Pixmap cursormask;
235         XGCValues xgc;
236         GC gc;
237         XColor dummycolour;
238         Cursor cursor;
239
240         cursormask = XCreatePixmap(display, root, 1, 1, 1);
241         xgc.function = GXclear;
242         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
243         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
244         dummycolour.pixel = 0;
245         dummycolour.red = 0;
246         dummycolour.flags = 04;
247         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
248         XFreePixmap(display,cursormask);
249         XFreeGC(display,gc);
250         return cursor;
251 }
252
253 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
254 {
255         static int originalmouseparms_num;
256         static int originalmouseparms_denom;
257         static int originalmouseparms_threshold;
258         static qboolean restore_spi;
259
260 #if !defined(__APPLE__) && !defined(SUNOS)
261         qboolean usedgamouse;
262 #endif
263
264         if (!vidx11_display || !win)
265                 return;
266
267         if (relative)
268                 fullscreengrab = true;
269
270         if (!mouse_avail)
271                 fullscreengrab = relative = hidecursor = false;
272
273 #if !defined(__APPLE__) && !defined(SUNOS)
274         usedgamouse = relative && vid_dgamouse.integer;
275         if (!vid_x11_dgasupported)
276                 usedgamouse = false;
277         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
278                 VID_SetMouse(false, false, false); // ungrab first!
279 #endif
280
281         if (vid_usingmousegrab != fullscreengrab)
282         {
283                 vid_usingmousegrab = fullscreengrab;
284                 cl_ignoremousemoves = 2;
285                 if (fullscreengrab)
286                 {
287                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
288                         if (vid_grabkeyboard.integer || vid_isfullscreen)
289                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
290                 }
291                 else
292                 {
293                         XUngrabPointer(vidx11_display, CurrentTime);
294                         XUngrabKeyboard(vidx11_display, CurrentTime);
295                 }
296         }
297
298         if (relative)
299         {
300                 if (!vid_usingmouse)
301                 {
302                         XWindowAttributes attribs_1;
303                         XSetWindowAttributes attribs_2;
304
305                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
306                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
307                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
308
309 #if !defined(__APPLE__) && !defined(SUNOS)
310                         vid_usingdgamouse = usedgamouse;
311                         if (usedgamouse)
312                         {
313                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
314                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
315                         }
316                         else
317 #endif
318                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
319
320 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
321 #if !defined(__APPLE__) && !defined(SUNOS)
322                         if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
323 #else
324                         if (!COM_CheckParm ("-noforcemparms"))
325 #endif
326                         {
327                                 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
328                                 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
329                                 restore_spi = true;
330                         }
331                         else
332                                 restore_spi = false;
333
334                         cl_ignoremousemoves = 2;
335                         vid_usingmouse = true;
336                 }
337         }
338         else
339         {
340                 if (vid_usingmouse)
341                 {
342 #if !defined(__APPLE__) && !defined(SUNOS)
343                         if (vid_usingdgamouse)
344                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
345                         vid_usingdgamouse = false;
346 #endif
347                         cl_ignoremousemoves = 2;
348
349                         if (restore_spi)
350                                 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
351                         restore_spi = false;
352
353                         vid_usingmouse = false;
354                 }
355         }
356
357         if (vid_usinghidecursor != hidecursor)
358         {
359                 vid_usinghidecursor = hidecursor;
360                 if (hidecursor)
361                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
362                 else
363                         XUndefineCursor(vidx11_display, win);
364         }
365 }
366
367 static keynum_t buttonremap[18] =
368 {
369         K_MOUSE1,
370         K_MOUSE3,
371         K_MOUSE2,
372         K_MWHEELUP,
373         K_MWHEELDOWN,
374         K_MOUSE4,
375         K_MOUSE5,
376         K_MOUSE6,
377         K_MOUSE7,
378         K_MOUSE8,
379         K_MOUSE9,
380         K_MOUSE10,
381         K_MOUSE11,
382         K_MOUSE12,
383         K_MOUSE13,
384         K_MOUSE14,
385         K_MOUSE15,
386         K_MOUSE16,
387 };
388
389 static void HandleEvents(void)
390 {
391         XEvent event;
392         int key;
393         char ascii;
394         qboolean dowarp = false;
395
396         if (!vidx11_display)
397                 return;
398
399         while (XPending(vidx11_display))
400         {
401                 XNextEvent(vidx11_display, &event);
402
403                 switch (event.type)
404                 {
405                 case KeyPress:
406                         // key pressed
407                         key = XLateKey (&event.xkey, &ascii);
408                         Key_Event(key, ascii, true);
409                         printf("keypress\n");
410                         break;
411
412                 case KeyRelease:
413                         // key released
414                         key = XLateKey (&event.xkey, &ascii);
415                         Key_Event(key, ascii, false);
416                         break;
417
418                 case MotionNotify:
419                         // mouse moved
420                         if (vid_usingmouse)
421                         {
422 #if !defined(__APPLE__) && !defined(SUNOS)
423                                 if (vid_usingdgamouse)
424                                 {
425                                         in_mouse_x += event.xmotion.x_root;
426                                         in_mouse_y += event.xmotion.y_root;
427                                 }
428                                 else
429 #endif
430                                 {
431                                         if (!event.xmotion.send_event)
432                                         {
433                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
434                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
435                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
436                                                 if (abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
437                                                         dowarp = true;
438                                         }
439                                 }
440                         }
441                         in_windowmouse_x = event.xmotion.x;
442                         in_windowmouse_y = event.xmotion.y;
443                         break;
444
445                 case ButtonPress:
446                         // mouse button pressed
447                         if (event.xbutton.button <= 18)
448                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
449                         else
450                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
451                         break;
452
453                 case ButtonRelease:
454                         // mouse button released
455                         if (event.xbutton.button <= 18)
456                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
457                         else
458                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
459                         break;
460
461                 case CreateNotify:
462                         // window created
463                         win_x = event.xcreatewindow.x;
464                         win_y = event.xcreatewindow.y;
465                         break;
466
467                 case ConfigureNotify:
468                         // window changed size/location
469                         win_x = event.xconfigure.x;
470                         win_y = event.xconfigure.y;
471                         if(vid_resizable.integer < 2)
472                         {
473                                 vid.width = event.xconfigure.width;
474                                 vid.height = event.xconfigure.height;
475                         }
476                         break;
477                 case DestroyNotify:
478                         // window has been destroyed
479                         Sys_Quit(0);
480                         break;
481                 case ClientMessage:
482                         // window manager messages
483                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
484                                 Sys_Quit(0);
485                         break;
486                 case MapNotify:
487                         if (vid.fullscreen)
488                                 break;
489                         // window restored
490                         vid_hidden = false;
491                         VID_RestoreSystemGamma();
492                         break;
493                 case UnmapNotify:
494                         if (vid.fullscreen)
495                                 break;
496                         // window iconified/rolledup/whatever
497                         vid_hidden = true;
498                         VID_RestoreSystemGamma();
499                         break;
500                 case FocusIn:
501                         if (vid.fullscreen)
502                                 break;
503                         // window is now the input focus
504                         vid_activewindow = true;
505                         break;
506                 case FocusOut:
507                         if (vid.fullscreen)
508                                 break;
509                         // window is no longer the input focus
510                         vid_activewindow = false;
511                         VID_RestoreSystemGamma();
512                         break;
513                 case EnterNotify:
514                         // mouse entered window
515                         break;
516                 case LeaveNotify:
517                         // mouse left window
518                         break;
519                 }
520         }
521
522         if (dowarp)
523         {
524                 /* move the mouse to the window center again */
525                 // we'll catch the warp motion by its send_event flag, updating the
526                 // stored mouse position without adding any delta motion
527                 XEvent event;
528                 event.type = MotionNotify;
529                 event.xmotion.display = vidx11_display;
530                 event.xmotion.window = win;
531                 event.xmotion.x = vid.width / 2;
532                 event.xmotion.y = vid.height / 2;
533                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
534                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
535         }
536 }
537
538 static void *prjobj = NULL;
539
540 static void GL_CloseLibrary(void)
541 {
542         if (prjobj)
543                 dlclose(prjobj);
544         prjobj = NULL;
545         gl_driver[0] = 0;
546         qglXGetProcAddressARB = NULL;
547         gl_extensions = "";
548         gl_platform = "";
549         gl_platformextensions = "";
550 }
551
552 static int GL_OpenLibrary(const char *name)
553 {
554         Con_Printf("Loading OpenGL driver %s\n", name);
555         GL_CloseLibrary();
556         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
557         {
558                 Con_Printf("Unable to open symbol list for %s\n", name);
559                 return false;
560         }
561         strlcpy(gl_driver, name, sizeof(gl_driver));
562         return true;
563 }
564
565 void *GL_GetProcAddress(const char *name)
566 {
567         void *p = NULL;
568         if (qglXGetProcAddressARB != NULL)
569                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
570         if (p == NULL)
571                 p = (void *) dlsym(prjobj, name);
572         return p;
573 }
574
575 void VID_Shutdown(void)
576 {
577         if (!ctx || !vidx11_display)
578                 return;
579
580         VID_SetMouse(false, false, false);
581         VID_RestoreSystemGamma();
582
583         // FIXME: glXDestroyContext here?
584         if (vid_isfullscreen)
585                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
586         if (win)
587                 XDestroyWindow(vidx11_display, win);
588         XCloseDisplay(vidx11_display);
589
590         vid_hidden = true;
591         vid_isfullscreen = false;
592         vidx11_display = NULL;
593         win = 0;
594         ctx = NULL;
595
596         GL_CloseLibrary();
597         Key_ClearStates ();
598 }
599
600 void signal_handler(int sig)
601 {
602         Con_Printf("Received signal %d, exiting...\n", sig);
603         VID_RestoreSystemGamma();
604         Sys_Quit(1);
605 }
606
607 void InitSig(void)
608 {
609         signal(SIGHUP, signal_handler);
610         signal(SIGINT, signal_handler);
611         signal(SIGQUIT, signal_handler);
612         signal(SIGILL, signal_handler);
613         signal(SIGTRAP, signal_handler);
614         signal(SIGIOT, signal_handler);
615         signal(SIGBUS, signal_handler);
616         signal(SIGFPE, signal_handler);
617         signal(SIGSEGV, signal_handler);
618         signal(SIGTERM, signal_handler);
619 }
620
621 void VID_Finish (void)
622 {
623         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
624         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
625         {
626                 vid_usingvsync = vid_usevsync;
627                 if (qglXSwapIntervalSGI (vid_usevsync))
628                         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");
629         }
630
631         if (r_render.integer)
632         {
633                 CHECKGLERROR
634                 if (r_speeds.integer || gl_finish.integer)
635                 {
636                         qglFinish();CHECKGLERROR
637                 }
638                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
639         }
640
641         if (vid_x11_hardwaregammasupported)
642                 VID_UpdateGamma(false, vid_x11_gammarampsize);
643 }
644
645 int VID_SetGamma(unsigned short *ramps, int rampsize)
646 {
647         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
648 }
649
650 int VID_GetGamma(unsigned short *ramps, int rampsize)
651 {
652         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
653 }
654
655 void VID_Init(void)
656 {
657 #if !defined(__APPLE__) && !defined(SUNOS)
658         Cvar_RegisterVariable (&vid_dgamouse);
659 #endif
660         InitSig(); // trap evil signals
661 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
662         if (COM_CheckParm ("-nomouse"))
663                 mouse_avail = false;
664 }
665
666 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
667 {
668         *attrib++ = GLX_RGBA;
669         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
670         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
671         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
672         *attrib++ = GLX_DOUBLEBUFFER;
673         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
674         // if stencil is enabled, ask for alpha too
675         if (stencil)
676         {
677                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
678                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
679         }
680         if (stereobuffer)
681                 *attrib++ = GLX_STEREO;
682         if (samples > 1)
683         {
684                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
685                 *attrib++ = 1;
686                 *attrib++ = GLX_SAMPLES_ARB;
687                 *attrib++ = samples;
688         }
689         *attrib++ = None;
690 }
691
692 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
693 {
694         int i;
695         int attrib[32];
696         XSetWindowAttributes attr;
697         XClassHint *clshints;
698         XWMHints *wmhints;
699         XSizeHints *szhints;
700         unsigned long mask;
701         Window root;
702         XVisualInfo *visinfo;
703         int MajorVersion, MinorVersion;
704         const char *drivername;
705
706 #if defined(__APPLE__) && defined(__MACH__)
707         drivername = "/usr/X11R6/lib/libGL.1.dylib";
708 #else
709         drivername = "libGL.so.1";
710 #endif
711 // 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
712 // 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
713 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
714         i = COM_CheckParm("-gl_driver");
715         if (i && i < com_argc - 1)
716                 drivername = com_argv[i + 1];
717         if (!GL_OpenLibrary(drivername))
718         {
719                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
720                 return false;
721         }
722
723         if (!(vidx11_display = XOpenDisplay(NULL)))
724         {
725                 Con_Print("Couldn't open the X display\n");
726                 return false;
727         }
728
729         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
730         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
731
732         vidx11_screen = DefaultScreen(vidx11_display);
733         root = RootWindow(vidx11_display, vidx11_screen);
734
735         // Get video mode list
736         MajorVersion = MinorVersion = 0;
737         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
738                 vidmode_ext = false;
739         else
740         {
741                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
742                 vidmode_ext = true;
743         }
744
745         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
746          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
747          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
748          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
749          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
750          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
751         {
752                 Con_Printf("glX functions not found in %s\n", gl_driver);
753                 return false;
754         }
755
756         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, samples);
757         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
758         if (!visinfo)
759         {
760                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
761                 return false;
762         }
763
764         if (vidmode_ext)
765         {
766                 int best_fit, best_dist, dist, x, y;
767
768                 // Are we going fullscreen?  If so, let's change video mode
769                 if (fullscreen)
770                 {
771                         XF86VidModeModeLine *current_vidmode;
772                         XF86VidModeModeInfo **vidmodes;
773                         int num_vidmodes;
774
775                         // This nice hack comes from the SDL source code
776                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
777                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
778
779                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
780                         best_dist = 9999999;
781                         best_fit = -1;
782
783                         for (i = 0; i < num_vidmodes; i++)
784                         {
785                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
786                                         continue;
787
788                                 x = width - vidmodes[i]->hdisplay;
789                                 y = height - vidmodes[i]->vdisplay;
790                                 dist = (x * x) + (y * y);
791                                 if (dist < best_dist)
792                                 {
793                                         best_dist = dist;
794                                         best_fit = i;
795                                 }
796                         }
797
798                         if (best_fit != -1)
799                         {
800                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
801                                 // to width/height =, so the window will take the full area of
802                                 // the mode chosen
803                                 width = vidmodes[best_fit]->hdisplay;
804                                 height = vidmodes[best_fit]->vdisplay;
805
806                                 // change to the mode
807                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
808                                 vid_isfullscreen = true;
809
810                                 // Move the viewport to top left
811                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
812                         }
813                         else
814                                 fullscreen = 0;
815
816                         free(vidmodes);
817                 }
818         }
819
820         // LordHavoc: save the visual for use in gamma ramp settings later
821         vidx11_visual = visinfo->visual;
822
823         /* window attributes */
824         attr.background_pixel = 0;
825         attr.border_pixel = 0;
826         // LordHavoc: save the colormap for later, too
827         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
828         attr.event_mask = X_MASK;
829         if (vid_isfullscreen)
830         {
831                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
832                 attr.override_redirect = True;
833                 attr.backing_store = NotUseful;
834                 attr.save_under = False;
835         }
836         else
837                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
838
839         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
840
841         wmhints = XAllocWMHints();
842         if(XpmCreatePixmapFromData(vidx11_display, win,
843                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
844                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
845                 wmhints->flags |= IconPixmapHint | IconMaskHint;
846
847         clshints = XAllocClassHint();
848         clshints->res_name = strdup(gamename);
849         clshints->res_class = strdup("DarkPlaces");
850
851         szhints = XAllocSizeHints();
852         if(vid_resizable.integer == 0)
853         {
854                 szhints->min_width = szhints->max_width = width;
855                 szhints->min_height = szhints->max_height = height;
856                 szhints->flags |= PMinSize | PMaxSize;
857         }
858
859         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
860         XFree(clshints);
861         XFree(wmhints);
862         XFree(szhints);
863         //XStoreName(vidx11_display, win, gamename);
864         XMapWindow(vidx11_display, win);
865
866         // LordHavoc: making the close button on a window do the right thing
867         // seems to involve this mess, sigh...
868         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
869         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
870
871         if (vid_isfullscreen)
872         {
873                 XMoveWindow(vidx11_display, win, 0, 0);
874                 XRaiseWindow(vidx11_display, win);
875                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
876                 XFlush(vidx11_display);
877                 // Move the viewport to top left
878                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
879         }
880
881         //XSync(vidx11_display, False);
882
883         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
884         if (!ctx)
885         {
886                 Con_Printf ("glXCreateContext failed\n");
887                 return false;
888         }
889
890         if (!qglXMakeCurrent(vidx11_display, win, ctx))
891         {
892                 Con_Printf ("glXMakeCurrent failed\n");
893                 return false;
894         }
895
896         XSync(vidx11_display, False);
897
898         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
899         {
900                 Con_Printf ("glGetString not found in %s\n", gl_driver);
901                 return false;
902         }
903
904         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
905         gl_platform = "GLX";
906         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
907
908         gl_videosyncavailable = false;
909
910 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
911 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
912 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
913         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
914 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
915 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
916 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
917         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
918
919         vid_usingmousegrab = false;
920         vid_usingmouse = false;
921         vid_usinghidecursor = false;
922         vid_usingvsync = false;
923         vid_hidden = false;
924         vid_activewindow = true;
925         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
926 #if !defined(__APPLE__) && !defined(SUNOS)
927         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
928         if (!vid_x11_dgasupported)
929                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
930 #endif
931         GL_Init();
932         return true;
933 }
934
935 void Sys_SendKeyEvents(void)
936 {
937         static qboolean sound_active = true;
938
939         // enable/disable sound on focus gain/loss
940         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
941         {
942                 if (!sound_active)
943                 {
944                         S_UnblockSound ();
945                         sound_active = true;
946                 }
947         }
948         else
949         {
950                 if (sound_active)
951                 {
952                         S_BlockSound ();
953                         sound_active = false;
954                 }
955         }
956
957         HandleEvents();
958 }
959
960 void IN_Move (void)
961 {
962 }