]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_agl.c
Remove v_hwgamma feature as it is not worth maintaining and has severe restrictions...
[xonotic/darkplaces.git] / vid_agl.c
1 /*
2         vid_agl.c
3
4         Mac OS X OpenGL and input module, using Carbon and AGL
5
6         Copyright (C) 2005-2006  Mathieu Olivier
7
8         This program is free software; you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation; either version 2 of the License, or
11         (at your option) any later version.
12
13         This program is distributed in the hope that it will be useful,
14         but WITHOUT ANY WARRANTY; without even the implied warranty of
15         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16         GNU General Public License for more details.
17
18         You should have received a copy of the GNU General Public License
19         along with this program; if not, write to the Free Software
20         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 */
22
23
24 #include <dlfcn.h>
25 #include <signal.h>
26 #include <AGL/agl.h>
27 #include <OpenGL/OpenGL.h>
28 #include <Carbon/Carbon.h>
29 #include <IOKit/hidsystem/IOHIDLib.h>
30 #include <IOKit/hidsystem/IOHIDParameter.h>
31 #include <IOKit/hidsystem/event_status_driver.h>
32 #include "quakedef.h"
33 #include "vid_agl_mackeys.h" // this is SDL/src/video/maccommon/SDL_mackeys.h
34
35 #ifndef kCGLCEMPEngine
36 #define kCGLCEMPEngine 313
37 #endif
38
39 // Tell startup code that we have a client
40 int cl_available = true;
41
42 qboolean vid_supportrefreshrate = true;
43
44 // AGL prototypes
45 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
46 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
47 GLboolean (*qaglDestroyContext) (AGLContext ctx);
48 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
49 const GLubyte* (*qaglErrorString) (GLenum code);
50 GLenum (*qaglGetError) (void);
51 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
52 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
53 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
54 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
55 void (*qaglSwapBuffers) (AGLContext ctx);
56 CGLError (*qCGLEnable) (CGLContextObj ctx, CGLContextEnable pname);
57 CGLError (*qCGLDisable) (CGLContextObj ctx, CGLContextEnable pname);
58 CGLContextObj (*qCGLGetCurrentContext) (void);
59
60 static qboolean multithreadedgl;
61 static qboolean mouse_avail = true;
62 static qboolean vid_usingmouse = false;
63 static qboolean vid_usinghidecursor = false;
64 static qboolean vid_usingnoaccel = false;
65
66 static qboolean vid_isfullscreen = false;
67 static qboolean vid_usingvsync = false;
68
69 static qboolean sound_active = true;
70
71 static cvar_t apple_multithreadedgl = {CVAR_SAVE, "apple_multithreadedgl", "1", "makes use of a second thread for the OpenGL driver (if possible) rather than using the engine thread (note: this is done automatically on most other operating systems)"};
72 static cvar_t apple_mouse_noaccel = {CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
73
74 static AGLContext context;
75 static WindowRef window;
76
77 static double originalMouseSpeed = -1.0;
78
79 io_connect_t IN_GetIOHandle(void)
80 {
81         io_connect_t iohandle = MACH_PORT_NULL;
82         kern_return_t status;
83         io_service_t iohidsystem = MACH_PORT_NULL;
84         mach_port_t masterport;
85
86         status = IOMasterPort(MACH_PORT_NULL, &masterport);
87         if(status != KERN_SUCCESS)
88                 return 0;
89
90         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
91         if(!iohidsystem)
92                 return 0;
93
94         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
95         IOObjectRelease(iohidsystem);
96
97         return iohandle;
98 }
99
100 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
101 {
102         if (!mouse_avail || !window)
103                 relative = hidecursor = false;
104
105         if (relative)
106         {
107                 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
108                         VID_SetMouse(false, false, false); // ungrab first!
109                 if (!vid_usingmouse)
110                 {
111                         Rect winBounds;
112                         CGPoint winCenter;
113
114                         SelectWindow(window);
115
116                         // Put the mouse cursor at the center of the window
117                         GetWindowBounds (window, kWindowContentRgn, &winBounds);
118                         winCenter.x = (winBounds.left + winBounds.right) / 2;
119                         winCenter.y = (winBounds.top + winBounds.bottom) / 2;
120                         CGWarpMouseCursorPosition(winCenter);
121
122                         // Lock the mouse pointer at its current position
123                         CGAssociateMouseAndMouseCursorPosition(false);
124
125                         // Save the status of mouse acceleration
126                         originalMouseSpeed = -1.0; // in case of error
127                         if(apple_mouse_noaccel.integer)
128                         {
129                                 io_connect_t mouseDev = IN_GetIOHandle();
130                                 if(mouseDev != 0)
131                                 {
132                                         if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
133                                         {
134                                                 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
135                                                 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
136                                                 {
137                                                         Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
138                                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
139                                                 }
140                                         }
141                                         else
142                                         {
143                                                 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
144                                                 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
145                                         }
146                                         IOServiceClose(mouseDev);
147                                 }
148                                 else
149                                 {
150                                         Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
151                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
152                                 }
153                         }
154
155                         vid_usingmouse = true;
156                         vid_usingnoaccel = !!apple_mouse_noaccel.integer;
157                 }
158         }
159         else
160         {
161                 if (vid_usingmouse)
162                 {
163                         if(originalMouseSpeed != -1.0)
164                         {
165                                 io_connect_t mouseDev = IN_GetIOHandle();
166                                 if(mouseDev != 0)
167                                 {
168                                         Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
169                                         if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
170                                                 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
171                                         IOServiceClose(mouseDev);
172                                 }
173                                 else
174                                         Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
175                         }
176
177                         CGAssociateMouseAndMouseCursorPosition(true);
178
179                         vid_usingmouse = false;
180                 }
181         }
182
183         if (vid_usinghidecursor != hidecursor)
184         {
185                 vid_usinghidecursor = hidecursor;
186                 if (hidecursor)
187                         CGDisplayHideCursor(CGMainDisplayID());
188                 else
189                         CGDisplayShowCursor(CGMainDisplayID());
190         }
191 }
192
193 void VID_Finish (void)
194 {
195         qboolean vid_usevsync;
196
197         // handle changes of the vsync option
198         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
199         if (vid_usingvsync != vid_usevsync)
200         {
201                 GLint sync = (vid_usevsync ? 1 : 0);
202
203                 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
204                 {
205                         vid_usingvsync = vid_usevsync;
206                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
207                 }
208                 else
209                         Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
210         }
211
212         if (!vid_hidden)
213         {
214                 if (r_speeds.integer == 2 || gl_finish.integer)
215                         GL_Finish();
216                 qaglSwapBuffers(context);
217         }
218         VID_UpdateGamma();
219
220         if (apple_multithreadedgl.integer)
221         {
222                 if (!multithreadedgl)
223                 {
224                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
225                         {
226                                 CGLContextObj ctx = qCGLGetCurrentContext();
227                                 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
228                                 if(e == kCGLNoError)
229                                         multithreadedgl = true;
230                                 else
231                                 {
232                                         Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
233                                         Cvar_SetValueQuick(&apple_multithreadedgl, 0);
234                                 }
235                         }
236                         else
237                         {
238                                 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
239                                 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
240                         }
241                 }
242         }
243         else
244         {
245                 if (multithreadedgl)
246                 {
247                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
248                         {
249                                 CGLContextObj ctx = qCGLGetCurrentContext();
250                                 qCGLDisable(ctx, kCGLCEMPEngine);
251                                 multithreadedgl = false;
252                         }
253                 }
254         }
255 }
256
257 void signal_handler(int sig)
258 {
259         Sys_PrintfToTerminal("Received signal %d, exiting...\n", sig);
260         Sys_Quit(1);
261 }
262
263 void InitSig(void)
264 {
265         signal(SIGHUP, signal_handler);
266         signal(SIGINT, signal_handler);
267         signal(SIGQUIT, signal_handler);
268         signal(SIGILL, signal_handler);
269         signal(SIGTRAP, signal_handler);
270         signal(SIGIOT, signal_handler);
271         signal(SIGBUS, signal_handler);
272         signal(SIGFPE, signal_handler);
273         signal(SIGSEGV, signal_handler);
274         signal(SIGTERM, signal_handler);
275 }
276
277 void VID_Init(void)
278 {
279         InitSig(); // trap evil signals
280         Cvar_RegisterVariable(&apple_multithreadedgl);
281         Cvar_RegisterVariable(&apple_mouse_noaccel);
282 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
283         if (COM_CheckParm ("-nomouse"))
284                 mouse_avail = false;
285 }
286
287 static void *prjobj = NULL;
288 static void *cglobj = NULL;
289
290 static void GL_CloseLibrary(void)
291 {
292         if (cglobj)
293                 dlclose(cglobj);
294         cglobj = NULL;
295         if (prjobj)
296                 dlclose(prjobj);
297         prjobj = NULL;
298         gl_driver[0] = 0;
299         gl_extensions = "";
300         gl_platform = "";
301         gl_platformextensions = "";
302 }
303
304 static int GL_OpenLibrary(void)
305 {
306         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
307         const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
308
309         Con_Printf("Loading OpenGL driver %s\n", name);
310         GL_CloseLibrary();
311         if (!(prjobj = dlopen(name, RTLD_LAZY)))
312         {
313                 Con_Printf("Unable to open symbol list for %s\n", name);
314                 return false;
315         }
316         strlcpy(gl_driver, name, sizeof(gl_driver));
317
318         Con_Printf("Loading OpenGL driver %s\n", name2);
319         if (!(cglobj = dlopen(name2, RTLD_LAZY)))
320                 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
321
322         return true;
323 }
324
325 void *GL_GetProcAddress(const char *name)
326 {
327         return dlsym(prjobj, name);
328 }
329
330 static void *CGL_GetProcAddress(const char *name)
331 {
332         if(!cglobj)
333                 return NULL;
334         return dlsym(cglobj, name);
335 }
336
337 void VID_Shutdown(void)
338 {
339         if (context == NULL && window == NULL)
340                 return;
341
342         VID_EnableJoystick(false);
343         VID_SetMouse(false, false, false);
344
345         if (context != NULL)
346         {
347                 qaglDestroyContext(context);
348                 context = NULL;
349         }
350
351         if (vid_isfullscreen)
352                 CGReleaseAllDisplays();
353
354         if (window != NULL)
355         {
356                 DisposeWindow(window);
357                 window = NULL;
358         }
359
360         vid_hidden = true;
361         vid_isfullscreen = false;
362
363         GL_CloseLibrary();
364         Key_ClearStates ();
365 }
366
367 // Since the event handler can be called at any time, we store the events for later processing
368 static qboolean AsyncEvent_Quitting = false;
369 static qboolean AsyncEvent_Collapsed = false;
370 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
371 {
372         OSStatus err = noErr;
373
374         switch (GetEventKind (event))
375         {
376                 case kEventWindowClosed:
377                         AsyncEvent_Quitting = true;
378                         break;
379
380                 // Docked (start)
381                 case kEventWindowCollapsing:
382                         AsyncEvent_Collapsed = true;
383                         break;
384
385                 // Undocked / restored (end)
386                 case kEventWindowExpanded:
387                         AsyncEvent_Collapsed = false;
388                         break;
389
390                 default:
391                         err = eventNotHandledErr;
392                         break;
393         }
394
395         return err;
396 }
397
398 static void VID_AppFocusChanged(qboolean windowIsActive)
399 {
400         if (vid_activewindow != windowIsActive)
401                 vid_activewindow = windowIsActive;
402
403         if (windowIsActive || !snd_mutewhenidle.integer)
404         {
405                 if (!sound_active)
406                 {
407                         S_UnblockSound ();
408                         sound_active = true;
409                 }
410         }
411         else
412         {
413                 if (sound_active)
414                 {
415                         S_BlockSound ();
416                         sound_active = false;
417                 }
418         }
419 }
420
421 static void VID_ProcessPendingAsyncEvents (void)
422 {
423         // Collapsed / expanded
424         if (AsyncEvent_Collapsed != vid_hidden)
425         {
426                 vid_hidden = !vid_hidden;
427                 VID_AppFocusChanged(!vid_hidden);
428         }
429
430         // Closed
431         if (AsyncEvent_Quitting)
432                 Sys_Quit(0);
433 }
434
435 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
436 {
437         *attrib++ = AGL_RGBA;
438         *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
439         *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
440         *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
441         *attrib++ = AGL_DOUBLEBUFFER;
442         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
443
444         // if stencil is enabled, ask for alpha too
445         if (stencil)
446         {
447                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
448                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
449         }
450         if (fullscreen)
451                 *attrib++ = AGL_FULLSCREEN;
452         if (stereobuffer)
453                 *attrib++ = AGL_STEREO;
454 #ifdef AGL_SAMPLE_BUFFERS_ARB
455 #ifdef AGL_SAMPLES_ARB
456         if (samples > 1)
457         {
458                 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
459                 *attrib++ = 1;
460                 *attrib++ = AGL_SAMPLES_ARB;
461                 *attrib++ = samples;
462         }
463 #endif
464 #endif
465
466         *attrib++ = AGL_NONE;
467 }
468
469 qboolean VID_InitMode(viddef_mode_t *mode)
470 {
471         const EventTypeSpec winEvents[] =
472         {
473                 { kEventClassWindow, kEventWindowClosed },
474                 { kEventClassWindow, kEventWindowCollapsing },
475                 { kEventClassWindow, kEventWindowExpanded },
476         };
477         OSStatus carbonError;
478         Rect windowBounds;
479         CFStringRef windowTitle;
480         AGLPixelFormat pixelFormat;
481         GLint attributes [32];
482         GLenum error;
483
484         if (!GL_OpenLibrary())
485         {
486                 Con_Printf("Unable to load GL driver\n");
487                 return false;
488         }
489
490         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
491          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
492          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
493          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
494          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
495          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
496          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
497          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
498          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
499          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
500          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
501         )
502         {
503                 Con_Printf("AGL functions not found\n");
504                 ReleaseWindow(window);
505                 return false;
506         }
507
508         qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
509         qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
510         qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
511         if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
512                 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
513
514         // Ignore the events from the previous window
515         AsyncEvent_Quitting = false;
516         AsyncEvent_Collapsed = false;
517
518         // Create the window, a bit towards the center of the screen
519         windowBounds.left = 100;
520         windowBounds.top = 100;
521         windowBounds.right = mode->width + 100;
522         windowBounds.bottom = mode->height + 100;
523         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
524         if (carbonError != noErr || window == NULL)
525         {
526                 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
527                 return false;
528         }
529
530         // Set the window title
531         windowTitle = CFSTR("DarkPlaces AGL");
532         SetWindowTitleWithCFString(window, windowTitle);
533
534         // Install the callback function for the window events we can't get
535         // through ReceiveNextEvent (i.e. close, collapse, and expand)
536         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
537                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
538
539         // Create the desired attribute list
540         VID_BuildAGLAttrib(attributes, mode->bitsperpixel == 32, mode->fullscreen, mode->stereobuffer, mode->samples);
541
542         if (!mode->fullscreen)
543         {
544                 // Output to Window
545                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
546                 error = qaglGetError();
547                 if (error != AGL_NO_ERROR)
548                 {
549                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
550                                         (char *)qaglErrorString(error));
551                         ReleaseWindow(window);
552                         return false;
553                 }
554         }
555         else  // Output is fullScreen
556         {
557                 CGDirectDisplayID mainDisplay;
558                 CFDictionaryRef refDisplayMode;
559                 GDHandle gdhDisplay;
560
561                 // Get the mainDisplay and set resolution to current
562                 mainDisplay = CGMainDisplayID();
563                 CGDisplayCapture(mainDisplay);
564
565                 // TOCHECK: not sure whether or not it's necessary to change the resolution
566                 // "by hand", or if aglSetFullscreen does the job anyway
567                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty(mainDisplay, mode->bitsperpixel, mode->width, mode->height, mode->refreshrate, kCGDisplayModeIsSafeForHardware, NULL);
568                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
569                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
570
571                 // Set pixel format with built attribs
572                 // Note: specifying a device is *required* for AGL_FullScreen
573                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
574                 error = qaglGetError();
575                 if (error != AGL_NO_ERROR)
576                 {
577                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
578                                                 (char *)qaglErrorString(error));
579                         ReleaseWindow(window);
580                         return false;
581                 }
582         }
583
584         // Create a context using the pform
585         context = qaglCreateContext(pixelFormat, NULL);
586         error = qaglGetError();
587         if (error != AGL_NO_ERROR)
588         {
589                 Con_Printf("qaglCreateContext FAILED: %s\n",
590                                         (char *)qaglErrorString(error));
591         }
592
593         // Make the context the current one ('enable' it)
594         qaglSetCurrentContext(context);
595         error = qaglGetError();
596         if (error != AGL_NO_ERROR)
597         {
598                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
599                                         (char *)qaglErrorString(error));
600                 ReleaseWindow(window);
601                 return false;
602         }
603
604         // Discard pform
605         qaglDestroyPixelFormat(pixelFormat);
606
607         // Attempt fullscreen if requested
608         if (mode->fullscreen)
609         {
610                 qaglSetFullScreen (context, mode->width, mode->height, mode->refreshrate, 0);
611                 error = qaglGetError();
612                 if (error != AGL_NO_ERROR)
613                 {
614                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
615                                                 (char *)qaglErrorString(error));
616                         return false;
617                 }
618         }
619         else
620         {
621                 // Set Window as Drawable
622                 qaglSetDrawable(context, GetWindowPort(window));
623                 error = qaglGetError();
624                 if (error != AGL_NO_ERROR)
625                 {
626                         Con_Printf("qaglSetDrawable FAILED: %s\n",
627                                                 (char *)qaglErrorString(error));
628                         ReleaseWindow(window);
629                         return false;
630                 }
631         }
632
633         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
634                 Sys_Error("glGetString not found in %s", gl_driver);
635
636         gl_platformextensions = "";
637         gl_platform = "AGL";
638
639         multithreadedgl = false;
640         vid_isfullscreen = mode->fullscreen;
641         vid_usingmouse = false;
642         vid_usinghidecursor = false;
643         vid_hidden = false;
644         vid_activewindow = true;
645         sound_active = true;
646         GL_Init();
647
648         SelectWindow(window);
649         ShowWindow(window);
650
651         return true;
652 }
653
654 static void Handle_KeyMod(UInt32 keymod)
655 {
656         const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
657         {
658                 { cmdKey,                                               K_AUX1 },
659                 { shiftKey,                                             K_SHIFT },
660                 { alphaLock,                                    K_CAPSLOCK },
661                 { optionKey,                                    K_ALT },
662                 { controlKey,                                   K_CTRL },
663                 { kEventKeyModifierNumLockMask, K_NUMLOCK },
664                 { kEventKeyModifierFnMask,              K_AUX2 }
665         };
666         static UInt32 prev_keymod = 0;
667         unsigned int i;
668         UInt32 modChanges;
669
670         modChanges = prev_keymod ^ keymod;
671         if (modChanges == 0)
672                 return;
673
674         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
675         {
676                 UInt32 keybit = keymod_events[i].keybit;
677
678                 if ((modChanges & keybit) != 0)
679                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
680         }
681
682         prev_keymod = keymod;
683 }
684
685 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
686 {
687         unsigned int keycode = 0;
688         char ascii = '\0';
689
690         switch (mackeycode)
691         {
692                 case MK_ESCAPE:
693                         keycode = K_ESCAPE;
694                         break;
695                 case MK_F1:
696                         keycode = K_F1;
697                         break;
698                 case MK_F2:
699                         keycode = K_F2;
700                         break;
701                 case MK_F3:
702                         keycode = K_F3;
703                         break;
704                 case MK_F4:
705                         keycode = K_F4;
706                         break;
707                 case MK_F5:
708                         keycode = K_F5;
709                         break;
710                 case MK_F6:
711                         keycode = K_F6;
712                         break;
713                 case MK_F7:
714                         keycode = K_F7;
715                         break;
716                 case MK_F8:
717                         keycode = K_F8;
718                         break;
719                 case MK_F9:
720                         keycode = K_F9;
721                         break;
722                 case MK_F10:
723                         keycode = K_F10;
724                         break;
725                 case MK_F11:
726                         keycode = K_F11;
727                         break;
728                 case MK_F12:
729                         keycode = K_F12;
730                         break;
731                 case MK_SCROLLOCK:
732                         keycode = K_SCROLLOCK;
733                         break;
734                 case MK_PAUSE:
735                         keycode = K_PAUSE;
736                         break;
737                 case MK_BACKSPACE:
738                         keycode = K_BACKSPACE;
739                         break;
740                 case MK_INSERT:
741                         keycode = K_INS;
742                         break;
743                 case MK_HOME:
744                         keycode = K_HOME;
745                         break;
746                 case MK_PAGEUP:
747                         keycode = K_PGUP;
748                         break;
749                 case MK_NUMLOCK:
750                         keycode = K_NUMLOCK;
751                         break;
752                 case MK_KP_EQUALS:
753                         keycode = K_KP_EQUALS;
754                         break;
755                 case MK_KP_DIVIDE:
756                         keycode = K_KP_DIVIDE;
757                         break;
758                 case MK_KP_MULTIPLY:
759                         keycode = K_KP_MULTIPLY;
760                         break;
761                 case MK_TAB:
762                         keycode = K_TAB;
763                         break;
764                 case MK_DELETE:
765                         keycode = K_DEL;
766                         break;
767                 case MK_END:
768                         keycode = K_END;
769                         break;
770                 case MK_PAGEDOWN:
771                         keycode = K_PGDN;
772                         break;
773                 case MK_KP7:
774                         keycode = K_KP_7;
775                         break;
776                 case MK_KP8:
777                         keycode = K_KP_8;
778                         break;
779                 case MK_KP9:
780                         keycode = K_KP_9;
781                         break;
782                 case MK_KP_MINUS:
783                         keycode = K_KP_MINUS;
784                         break;
785                 case MK_CAPSLOCK:
786                         keycode = K_CAPSLOCK;
787                         break;
788                 case MK_RETURN:
789                         keycode = K_ENTER;
790                         break;
791                 case MK_KP4:
792                         keycode = K_KP_4;
793                         break;
794                 case MK_KP5:
795                         keycode = K_KP_5;
796                         break;
797                 case MK_KP6:
798                         keycode = K_KP_6;
799                         break;
800                 case MK_KP_PLUS:
801                         keycode = K_KP_PLUS;
802                         break;
803                 case MK_KP1:
804                         keycode = K_KP_1;
805                         break;
806                 case MK_KP2:
807                         keycode = K_KP_2;
808                         break;
809                 case MK_KP3:
810                         keycode = K_KP_3;
811                         break;
812                 case MK_KP_ENTER:
813                 case MK_IBOOK_ENTER:
814                         keycode = K_KP_ENTER;
815                         break;
816                 case MK_KP0:
817                         keycode = K_KP_0;
818                         break;
819                 case MK_KP_PERIOD:
820                         keycode = K_KP_PERIOD;
821                         break;
822                 default:
823                         switch(charcode)
824                         {
825                                 case kUpArrowCharCode:
826                                         keycode = K_UPARROW;
827                                         break;
828                                 case kLeftArrowCharCode:
829                                         keycode = K_LEFTARROW;
830                                         break;
831                                 case kDownArrowCharCode:
832                                         keycode = K_DOWNARROW;
833                                         break;
834                                 case kRightArrowCharCode:
835                                         keycode = K_RIGHTARROW;
836                                         break;
837                                 case 0:
838                                 case 191:
839                                         // characters 0 and 191 are sent by the mouse buttons (?!)
840                                         break;
841                                 default:
842                                         if ('A' <= charcode && charcode <= 'Z')
843                                         {
844                                                 keycode = charcode + ('a' - 'A');  // lowercase it
845                                                 ascii = charcode;
846                                         }
847                                         else if (charcode >= 32)
848                                         {
849                                                 keycode = charcode;
850                                                 ascii = charcode;
851                                         }
852                                         else
853                                                 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
854                         }
855         }
856
857         if (keycode != 0)
858                 Key_Event(keycode, ascii, keypressed);
859 }
860
861 void Sys_SendKeyEvents(void)
862 {
863         EventRef theEvent;
864         EventTargetRef theTarget;
865
866         // Start by processing the asynchronous events we received since the previous frame
867         VID_ProcessPendingAsyncEvents();
868
869         theTarget = GetEventDispatcherTarget();
870         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
871         {
872                 UInt32 eventClass = GetEventClass(theEvent);
873                 UInt32 eventKind = GetEventKind(theEvent);
874
875                 switch (eventClass)
876                 {
877                         case kEventClassMouse:
878                         {
879                                 EventMouseButton theButton;
880                                 int key;
881
882                                 switch (eventKind)
883                                 {
884                                         case kEventMouseDown:
885                                         case kEventMouseUp:
886                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
887                                                 switch (theButton)
888                                                 {
889                                                         default:
890                                                         case kEventMouseButtonPrimary:
891                                                                 key = K_MOUSE1;
892                                                                 break;
893                                                         case kEventMouseButtonSecondary:
894                                                                 key = K_MOUSE2;
895                                                                 break;
896                                                         case kEventMouseButtonTertiary:
897                                                                 key = K_MOUSE3;
898                                                                 break;
899                                                 }
900                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
901                                                 break;
902
903                                         // Note: These two events are mutual exclusives
904                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
905                                         case kEventMouseMoved:
906                                         case kEventMouseDragged:
907                                         {
908                                                 HIPoint deltaPos;
909                                                 HIPoint windowPos;
910
911                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
912                                                 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
913
914                                                 if (vid_usingmouse)
915                                                 {
916                                                         in_mouse_x += deltaPos.x;
917                                                         in_mouse_y += deltaPos.y;
918                                                 }
919
920                                                 in_windowmouse_x = windowPos.x;
921                                                 in_windowmouse_y = windowPos.y;
922                                                 break;
923                                         }
924
925                                         case kEventMouseWheelMoved:
926                                         {
927                                                 SInt32 delta;
928                                                 unsigned int wheelEvent;
929
930                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
931
932                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
933                                                 Key_Event(wheelEvent, 0, true);
934                                                 Key_Event(wheelEvent, 0, false);
935                                                 break;
936                                         }
937
938                                         default:
939                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
940                                                 break;
941                                 }
942                         }
943
944                         case kEventClassKeyboard:
945                         {
946                                 char charcode;
947                                 UInt32 keycode;
948
949                                 switch (eventKind)
950                                 {
951                                         case kEventRawKeyDown:
952                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
953                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
954                                                 Handle_Key(charcode, keycode, true);
955                                                 break;
956
957                                         case kEventRawKeyRepeat:
958                                                 break;
959
960                                         case kEventRawKeyUp:
961                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
962                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
963                                                 Handle_Key(charcode, keycode, false);
964                                                 break;
965
966                                         case kEventRawKeyModifiersChanged:
967                                         {
968                                                 UInt32 keymod = 0;
969                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
970                                                 Handle_KeyMod(keymod);
971                                                 break;
972                                         }
973
974                                         case kEventHotKeyPressed:
975                                                 break;
976
977                                         case kEventHotKeyReleased:
978                                                 break;
979
980                                         case kEventMouseWheelMoved:
981                                                 break;
982
983                                         default:
984                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
985                                                 break;
986                                 }
987                                 break;
988                         }
989
990                         case kEventClassTextInput:
991                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
992                                 break;
993
994                         case kEventClassApplication:
995                                 switch (eventKind)
996                                 {
997                                         case kEventAppActivated :
998                                                 VID_AppFocusChanged(true);
999                                                 break;
1000                                         case kEventAppDeactivated:
1001                                                 VID_AppFocusChanged(false);
1002                                                 break;
1003                                         case kEventAppQuit:
1004                                                 Sys_Quit(0);
1005                                                 break;
1006                                         case kEventAppActiveWindowChanged:
1007                                                 break;
1008                                         default:
1009                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1010                                                 break;
1011                                 }
1012                                 break;
1013
1014                         case kEventClassAppleEvent:
1015                                 switch (eventKind)
1016                                 {
1017                                         case kEventAppleEvent :
1018                                                 break;
1019                                         default:
1020                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1021                                                 break;
1022                                 }
1023                                 break;
1024
1025                         case kEventClassWindow:
1026                                 switch (eventKind)
1027                                 {
1028                                         case kEventWindowUpdate :
1029                                                 break;
1030                                         default:
1031                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1032                                                 break;
1033                                 }
1034                                 break;
1035
1036                         case kEventClassControl:
1037                                 break;
1038
1039                         default:
1040                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1041                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
1042                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1043                                                         eventKind);*/
1044                                 break;
1045                 }
1046
1047                 SendEventToEventTarget (theEvent, theTarget);
1048                 ReleaseEvent(theEvent);
1049         }
1050 }
1051
1052 void VID_BuildJoyState(vid_joystate_t *joystate)
1053 {
1054         VID_Shared_BuildJoyState_Begin(joystate);
1055         VID_Shared_BuildJoyState_Finish(joystate);
1056 }
1057
1058 void VID_EnableJoystick(qboolean enable)
1059 {
1060         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1061         qboolean success = false;
1062         int sharedcount = 0;
1063         sharedcount = VID_Shared_SetJoystick(index);
1064         if (index >= 0 && index < sharedcount)
1065                 success = true;
1066
1067         // update cvar containing count of XInput joysticks
1068         if (joy_detected.integer != sharedcount)
1069                 Cvar_SetValueQuick(&joy_detected, sharedcount);
1070
1071         Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1072 }
1073
1074 void IN_Move (void)
1075 {
1076         vid_joystate_t joystate;
1077         VID_EnableJoystick(true);
1078         VID_BuildJoyState(&joystate);
1079         VID_ApplyJoyState(&joystate);
1080 }
1081
1082 static bool GetDictionaryBoolean(CFDictionaryRef d, const void *key)
1083 {
1084     CFBooleanRef ref = (CFBooleanRef) CFDictionaryGetValue(d, key);
1085     if(ref)
1086         return CFBooleanGetValue(ref);
1087     return false;
1088 }
1089
1090 long GetDictionaryLong(CFDictionaryRef d, const void *key)
1091 {
1092         long value = 0;
1093     CFNumberRef ref = (CFNumberRef) CFDictionaryGetValue(d, key);
1094     if(ref)
1095         CFNumberGetValue(ref, kCFNumberLongType, &value);
1096     return value;
1097 }
1098
1099 vid_mode_t *VID_GetDesktopMode(void)
1100 {
1101         return NULL; // FIXME add desktopfullscreen
1102 }
1103
1104 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1105 {
1106         CGDirectDisplayID mainDisplay = CGMainDisplayID();
1107         CFArrayRef vidmodes = CGDisplayAvailableModes(mainDisplay);
1108         CFDictionaryRef thismode;
1109         unsigned int n = CFArrayGetCount(vidmodes);
1110         unsigned int i;
1111         size_t k;
1112
1113         k = 0;
1114         for(i = 0; i < n; ++i)
1115         {
1116                 thismode = (CFDictionaryRef) CFArrayGetValueAtIndex(vidmodes, i);
1117                 if(!GetDictionaryBoolean(thismode, kCGDisplayModeIsSafeForHardware))
1118                         continue;
1119
1120                 if(k >= maxcount)
1121                         break;
1122                 modes[k].width = GetDictionaryLong(thismode, kCGDisplayWidth);
1123                 modes[k].height = GetDictionaryLong(thismode, kCGDisplayHeight);
1124                 modes[k].bpp = GetDictionaryLong(thismode, kCGDisplayBitsPerPixel);
1125                 modes[k].refreshrate = GetDictionaryLong(thismode, kCGDisplayRefreshRate);
1126                 modes[k].pixelheight_num = 1;
1127                 modes[k].pixelheight_denom = 1; // OS X doesn't expose this either
1128                 ++k;
1129         }
1130         return k;
1131 }