2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 //#include <termios.h>
21 //#include <sys/ioctl.h>
22 //#include <sys/stat.h>
31 #include <X11/Xutil.h>
34 #include <X11/keysym.h>
35 #include <X11/cursorfont.h>
37 #include <X11/extensions/XShm.h>
38 #include <X11/extensions/xf86dga.h>
39 #include <X11/extensions/xf86vmode.h>
43 int cl_available = true;
46 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
47 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
48 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
49 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
50 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
51 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
53 //GLX_ARB_get_proc_address
54 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
56 static gl_extensionfunctionlist_t getprocaddressfuncs[] =
58 {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
63 GLint (GLAPIENTRY *qglXGetVideoSyncSGI)(GLuint *count);
64 GLint (GLAPIENTRY *qglXWaitVideoSyncSGI)(int divisor, int remainder, unsigned int *count);
66 static gl_extensionfunctionlist_t videosyncfuncs[] =
68 {"glXGetVideoSyncSGI", (void **) &qglXGetVideoSyncSGI},
69 {"glXWaitVideoSyncSGI", (void **) &qglXWaitVideoSyncSGI},
73 static Display *vidx11_display = NULL;
76 static GLXContext ctx = NULL;
78 Atom wm_delete_window_atom;
80 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
81 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
82 PointerMotionMask | ButtonMotionMask )
83 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | StructureNotifyMask )
86 static qboolean mouse_avail = true;
87 static qboolean mouse_active = false, usingmouse = false;
88 static float mouse_x, mouse_y;
89 static int p_mouse_x, p_mouse_y;
91 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
92 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
94 qboolean vidmode_ext = false;
96 static int win_x, win_y;
98 static int scr_width, scr_height;
100 static XF86VidModeModeInfo **vidmodes;
101 static int num_vidmodes;
102 static qboolean vidmode_active = false;
104 static Visual *vidx11_visual;
105 static Colormap vidx11_colormap;
107 /*-----------------------------------------------------------------------*/
110 XLateKey(XKeyEvent *ev)
115 keysym = XLookupKeysym(ev, 0);
119 case XK_KP_Page_Up: key = KP_PGUP; break;
120 case XK_Page_Up: key = K_PGUP; break;
122 case XK_KP_Page_Down: key = KP_PGDN; break;
123 case XK_Page_Down: key = K_PGDN; break;
125 case XK_KP_Home: key = KP_HOME; break;
126 case XK_Home: key = K_HOME; break;
128 case XK_KP_End: key = KP_END; break;
129 case XK_End: key = K_END; break;
131 case XK_KP_Left: key = KP_LEFTARROW; break;
132 case XK_Left: key = K_LEFTARROW; break;
134 case XK_KP_Right: key = KP_RIGHTARROW; break;
135 case XK_Right: key = K_RIGHTARROW; break;
137 case XK_KP_Down: key = KP_DOWNARROW; break;
138 case XK_Down: key = K_DOWNARROW; break;
140 case XK_KP_Up: key = KP_UPARROW; break;
141 case XK_Up: key = K_UPARROW; break;
143 case XK_Escape: key = K_ESCAPE; break;
145 case XK_KP_Enter: key = KP_ENTER; break;
146 case XK_Return: key = K_ENTER; break;
148 case XK_Tab: key = K_TAB; break;
150 case XK_F1: key = K_F1; break;
151 case XK_F2: key = K_F2; break;
152 case XK_F3: key = K_F3; break;
153 case XK_F4: key = K_F4; break;
154 case XK_F5: key = K_F5; break;
155 case XK_F6: key = K_F6; break;
156 case XK_F7: key = K_F7; break;
157 case XK_F8: key = K_F8; break;
158 case XK_F9: key = K_F9; break;
159 case XK_F10: key = K_F10; break;
160 case XK_F11: key = K_F11; break;
161 case XK_F12: key = K_F12; break;
163 case XK_BackSpace: key = K_BACKSPACE; break;
165 case XK_KP_Delete: key = KP_DEL; break;
166 case XK_Delete: key = K_DEL; break;
168 case XK_Pause: key = K_PAUSE; break;
171 case XK_Shift_R: key = K_SHIFT; break;
175 case XK_Control_R: key = K_CTRL; break;
181 case XK_Meta_R: key = K_ALT; break;
183 case XK_Caps_Lock: key = K_CAPSLOCK; break;
184 case XK_KP_Begin: key = KP_5; break;
186 case XK_Insert: key = K_INS; break;
187 case XK_KP_Insert: key = KP_INS; break;
189 case XK_KP_Multiply: key = KP_MULTIPLY; break;
190 case XK_KP_Add: key = KP_PLUS; break;
191 case XK_KP_Subtract: key = KP_MINUS; break;
192 case XK_KP_Divide: key = KP_DIVIDE; break;
194 /* For Sun keyboards */
195 case XK_F27: key = K_HOME; break;
196 case XK_F29: key = K_PGUP; break;
197 case XK_F33: key = K_END; break;
198 case XK_F35: key = K_PGDN; break;
205 if ((key >= 'A') && (key <= 'Z'))
206 key = key + ('a' - 'A');
214 static Cursor CreateNullCursor(Display *display, Window root)
222 cursormask = XCreatePixmap(display, root, 1, 1, 1);
223 xgc.function = GXclear;
224 gc = XCreateGC(display, cursormask, GCFunction, &xgc);
225 XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
226 dummycolour.pixel = 0;
228 dummycolour.flags = 04;
229 cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
230 XFreePixmap(display,cursormask);
235 static void install_grabs(void)
237 XWindowAttributes attribs_1;
238 XSetWindowAttributes attribs_2;
240 XGetWindowAttributes(vidx11_display, win, &attribs_1);
241 attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
242 XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
245 XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
247 XGrabPointer(vidx11_display, win, True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
251 int MajorVersion, MinorVersion;
253 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
255 // unable to query, probalby not supported
256 Con_Printf( "Failed to detect XF86DGA Mouse\n" );
262 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
263 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
267 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
269 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
272 mouse_x = mouse_y = 0;
275 static void uninstall_grabs(void)
277 if (!vidx11_display || !win)
280 if (vid_dga.integer == 1)
281 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
283 XUngrabPointer(vidx11_display, CurrentTime);
284 XUngrabKeyboard(vidx11_display, CurrentTime);
287 XUndefineCursor(vidx11_display, win);
289 mouse_active = false;
292 static void HandleEvents(void)
295 qboolean dowarp = false;
300 while (XPending(vidx11_display))
302 XNextEvent(vidx11_display, &event);
308 Key_Event(XLateKey(&event.xkey), true);
313 Key_Event(XLateKey(&event.xkey), false);
320 if (vid_dga.integer == 1)
322 mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
323 mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
328 if (!event.xmotion.send_event)
330 mouse_x += event.xmotion.x - p_mouse_x;
331 mouse_y += event.xmotion.y - p_mouse_y;
332 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
335 p_mouse_x = event.xmotion.x;
336 p_mouse_y = event.xmotion.y;
340 ui_mouseupdate(event.xmotion.x, event.xmotion.y);
344 // mouse button pressed
345 switch(event.xbutton.button)
348 Key_Event(K_MOUSE1, true);
351 Key_Event(K_MOUSE3, true);
354 Key_Event(K_MOUSE2, true);
357 Key_Event(K_MWHEELUP, true);
360 Key_Event(K_MWHEELDOWN, true);
363 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-5 expected\n", event.xbutton.button);
369 // mouse button released
370 switch(event.xbutton.button)
373 Key_Event(K_MOUSE1, false);
376 Key_Event(K_MOUSE3, false);
379 Key_Event(K_MOUSE2, false);
382 Key_Event(K_MWHEELUP, false);
385 Key_Event(K_MWHEELDOWN, false);
388 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-5 expected\n", event.xbutton.button);
395 win_x = event.xcreatewindow.x;
396 win_y = event.xcreatewindow.y;
399 case ConfigureNotify:
400 // window changed size/location
401 win_x = event.xconfigure.x;
402 win_y = event.xconfigure.y;
405 // window has been destroyed
409 // window manager messages
410 if ((event.xclient.format == 32) && (event.xclient.data.l[0] == wm_delete_window_atom))
418 // window iconified/rolledup/whatever
422 // window is now the input focus
425 // window is no longer the input focus
428 // mouse entered window
438 /* move the mouse to the window center again */
439 p_mouse_x = scr_width / 2;
440 p_mouse_y = scr_height / 2;
441 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
446 static void IN_DeactivateMouse( void )
448 if (!mouse_avail || !vidx11_display || !win)
454 mouse_active = false;
458 static void IN_ActivateMouse( void )
460 if (!mouse_avail || !vidx11_display || !win)
465 mouse_x = mouse_y = 0; // don't spazz
472 void VID_Shutdown(void)
474 if (!ctx || !vidx11_display)
483 // FIXME: glXDestroyContext here?
485 XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[0]);
487 XDestroyWindow(vidx11_display, win);
488 XCloseDisplay(vidx11_display);
490 vidmode_active = false;
491 vidx11_display = NULL;
498 void signal_handler(int sig)
500 printf("Received signal %d, exiting...\n", sig);
507 signal(SIGHUP, signal_handler);
508 signal(SIGINT, signal_handler);
509 signal(SIGQUIT, signal_handler);
510 signal(SIGILL, signal_handler);
511 signal(SIGTRAP, signal_handler);
512 signal(SIGIOT, signal_handler);
513 signal(SIGBUS, signal_handler);
514 signal(SIGFPE, signal_handler);
515 signal(SIGSEGV, signal_handler);
516 signal(SIGTERM, signal_handler);
524 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
528 *height = scr_height;
531 void VID_Finish (void)
534 if (r_render.integer)
537 qglXSwapBuffers(vidx11_display, win);
540 // handle the mouse state when windowed if that's changed
542 if (vid_mouse.integer && !key_consoleactive)
559 IN_DeactivateMouse ();
564 // LordHavoc: ported from SDL 1.2.2, this was far more difficult to port from
565 // SDL than to simply use the XFree gamma ramp extension, but that affects the
566 // whole screen even when the game window is inactive, this only affects the
567 // screen while the window is active, very desirable behavior :)
568 int VID_SetGamma(float prescale, float gamma, float scale, float base)
570 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
575 unsigned int Rmask, Gmask, Bmask, Rloss, Gloss, Bloss, Rshift, Gshift, Bshift, mask;
577 unsigned short ramp[256];
579 if (COM_CheckParm("-nogamma"))
582 if (vidx11_visual->class != DirectColor)
584 Con_Printf("X11 Visual class is %d, can only do gamma on %d\n", vidx11_visual->class, DirectColor);
588 Rmask = vidx11_visual->red_mask;
589 Gmask = vidx11_visual->green_mask;
590 Bmask = vidx11_visual->blue_mask;
596 for (;!(mask & 1);mask >>= 1)
598 for (;(mask & 1);mask >>= 1)
605 for (;!(mask & 1);mask >>= 1)
607 for (;(mask & 1);mask >>= 1)
614 for (;!(mask & 1);mask >>= 1)
616 for (;(mask & 1);mask >>= 1)
620 BuildGammaTable16(prescale, gamma, scale, base, ramp);
622 // convert gamma ramp to palette (yes this seems odd)
623 ncolors = vidx11_visual->map_entries;
624 for (i = 0;i < ncolors;i++)
626 c = (256 * i / ncolors);
627 xcmap[i].pixel = ((c >> Rloss) << Rshift) | ((c >> Gloss) << Gshift) | ((c >> Bloss) << Bshift);
628 xcmap[i].red = ramp[c];
629 xcmap[i].green = ramp[c];
630 xcmap[i].blue = ramp[c];
631 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
633 XStoreColors(vidx11_display, vidx11_colormap, xcmap, ncolors);
634 XSync(vidx11_display, false);
635 // FIXME: should this check for BadAccess/BadColor/BadValue errors produced by XStoreColors before setting this true?
642 Cvar_RegisterVariable (&vid_dga);
643 Cvar_RegisterVariable (&vid_dga_mouseaccel);
644 InitSig(); // trap evil signals
645 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
649 void VID_BuildGLXAttrib(int *attrib, int stencil, int gamma)
651 *attrib++ = GLX_RGBA;
652 *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
653 *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
654 *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
655 *attrib++ = GLX_DOUBLEBUFFER;
656 *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
657 // if stencil is enabled, ask for alpha too
660 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
661 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
665 *attrib++ = GLX_X_VISUAL_TYPE;*attrib++ = GLX_DIRECT_COLOR;
670 int VID_InitMode(int fullscreen, int width, int height, int bpp, int stencil)
674 XSetWindowAttributes attr;
677 XVisualInfo *visinfo;
678 int MajorVersion, MinorVersion;
679 const char *drivername;
681 drivername = "libGL.so.1";
682 i = COM_CheckParm("-gl_driver");
683 if (i && i < com_argc - 1)
684 drivername = com_argv[i + 1];
685 if (!GL_OpenLibrary(drivername))
687 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
691 if (!(vidx11_display = XOpenDisplay(NULL)))
693 Con_Printf("Couldn't open the X display\n");
697 scrnum = DefaultScreen(vidx11_display);
698 root = RootWindow(vidx11_display, scrnum);
700 // Get video mode list
701 MajorVersion = MinorVersion = 0;
702 if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
706 Con_Printf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
710 if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
711 || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
712 || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
713 || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
714 || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
716 Con_Printf("glX functions not found in %s\n", gl_driver);
721 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
723 if (!COM_CheckParm("-nogamma"))
725 VID_BuildGLXAttrib(attrib, stencil, true);
726 visinfo = qglXChooseVisual(vidx11_display, scrnum, attrib);
731 VID_BuildGLXAttrib(attrib, stencil, false);
732 visinfo = qglXChooseVisual(vidx11_display, scrnum, attrib);
735 Con_Printf("Couldn't get an RGB, Double-buffered, Depth visual\n");
742 int best_fit, best_dist, dist, x, y;
744 XF86VidModeGetAllModeLines(vidx11_display, scrnum, &num_vidmodes, &vidmodes);
746 // Are we going fullscreen? If so, let's change video mode
752 for (i = 0; i < num_vidmodes; i++)
754 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
757 x = width - vidmodes[i]->hdisplay;
758 y = height - vidmodes[i]->vdisplay;
759 dist = (x * x) + (y * y);
760 if (dist < best_dist)
769 // LordHavoc: changed from ActualWidth/ActualHeight =,
770 // to width/height =, so the window will take the full area of
772 width = vidmodes[best_fit]->hdisplay;
773 height = vidmodes[best_fit]->vdisplay;
775 // change to the mode
776 XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[best_fit]);
777 vidmode_active = true;
779 // Move the viewport to top left
780 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
787 // LordHavoc: save the visual for use in gamma ramp settings later
788 vidx11_visual = visinfo->visual;
790 /* window attributes */
791 attr.background_pixel = 0;
792 attr.border_pixel = 0;
793 // LordHavoc: save the colormap for later, too
794 vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
795 attr.event_mask = X_MASK;
798 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
799 attr.override_redirect = True;
800 attr.backing_store = NotUseful;
801 attr.save_under = False;
804 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
806 win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
807 XStoreName(vidx11_display, win, gamename);
808 XMapWindow(vidx11_display, win);
810 // LordHavoc: making the close button on a window do the right thing
811 // seems to involve this mess, sigh...
812 wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
813 XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
817 XMoveWindow(vidx11_display, win, 0, 0);
818 XRaiseWindow(vidx11_display, win);
819 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
820 XFlush(vidx11_display);
821 // Move the viewport to top left
822 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
825 //XSync(vidx11_display, False);
827 ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
829 Sys_Error ("glXCreateContext failed\n");
831 if (!qglXMakeCurrent(vidx11_display, win, ctx))
832 Sys_Error ("glXMakeCurrent failed\n");
834 XSync(vidx11_display, False);
839 if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
840 Sys_Error("glGetString not found in %s", gl_driver);
842 gl_renderer = qglGetString(GL_RENDERER);
843 gl_vendor = qglGetString(GL_VENDOR);
844 gl_version = qglGetString(GL_VERSION);
845 gl_extensions = qglGetString(GL_EXTENSIONS);
847 gl_platformextensions = qglXQueryExtensionsString(vidx11_display, scrnum);
849 GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
850 gl_videosyncavailable = GL_CheckExtension("GLX_SGI_video_sync", videosyncfuncs, "-novideosync", false);
858 void Sys_SendKeyEvents(void)
868 void IN_Commands (void)
872 void IN_Move (usercmd_t *cmd)
875 IN_Mouse(cmd, mouse_x, mouse_y);
880 static void *prjobj = NULL;
882 int GL_OpenLibrary(const char *name)
884 Con_Printf("Loading GL driver %s\n", name);
886 if (!(prjobj = dlopen(name, RTLD_LAZY)))
888 Con_Printf("Unable to open symbol list for %s\n", name);
891 strcpy(gl_driver, name);
895 void GL_CloseLibrary(void)
901 qglXGetProcAddressARB = NULL;
904 gl_platformextensions = "";
907 void *GL_GetProcAddress(const char *name)
910 if (qglXGetProcAddressARB != NULL)
911 p = (void *) qglXGetProcAddressARB(name);
913 p = (void *) dlsym(prjobj, name);