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