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