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