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