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