]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_agl.c
added Sys_PrintfToTerminal function for convenience, this replaces
[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 #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 (!vid_hidden)
214         {
215                 if (r_speeds.integer == 2 || gl_finish.integer)
216                         GL_Finish();
217                 qaglSwapBuffers(context);
218         }
219         VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
220
221         if (apple_multithreadedgl.integer)
222         {
223                 if (!multithreadedgl)
224                 {
225                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
226                         {
227                                 CGLContextObj ctx = qCGLGetCurrentContext();
228                                 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
229                                 if(e == kCGLNoError)
230                                         multithreadedgl = true;
231                                 else
232                                 {
233                                         Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
234                                         Cvar_SetValueQuick(&apple_multithreadedgl, 0);
235                                 }
236                         }
237                         else
238                         {
239                                 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
240                                 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
241                         }
242                 }
243         }
244         else
245         {
246                 if (multithreadedgl)
247                 {
248                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
249                         {
250                                 CGLContextObj ctx = qCGLGetCurrentContext();
251                                 qCGLDisable(ctx, kCGLCEMPEngine);
252                                 multithreadedgl = false;
253                         }
254                 }
255         }
256 }
257
258 int VID_SetGamma(unsigned short *ramps, int rampsize)
259 {
260         CGGammaValue table_red [GAMMA_TABLE_SIZE];
261         CGGammaValue table_green [GAMMA_TABLE_SIZE];
262         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
263         int i;
264
265         // Convert the unsigned short table into 3 float tables
266         for (i = 0; i < rampsize; i++)
267                 table_red[i] = (float)ramps[i] / 65535.0f;
268         for (i = 0; i < rampsize; i++)
269                 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
270         for (i = 0; i < rampsize; i++)
271                 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
272
273         if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
274         {
275                 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
276                 return false;
277         }
278
279         return true;
280 }
281
282 int VID_GetGamma(unsigned short *ramps, int rampsize)
283 {
284         CGGammaValue table_red [GAMMA_TABLE_SIZE];
285         CGGammaValue table_green [GAMMA_TABLE_SIZE];
286         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
287         CGTableCount actualsize = 0;
288         int i;
289
290         // Get the gamma ramps from the system
291         if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
292         {
293                 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
294                 return false;
295         }
296         if (actualsize != (unsigned int)rampsize)
297         {
298                 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
299                 return false;
300         }
301
302         // Convert the 3 float tables into 1 unsigned short table
303         for (i = 0; i < rampsize; i++)
304                 ramps[i] = table_red[i] * 65535.0f;
305         for (i = 0; i < rampsize; i++)
306                 ramps[i + rampsize] = table_green[i] * 65535.0f;
307         for (i = 0; i < rampsize; i++)
308                 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
309
310         return true;
311 }
312
313 void signal_handler(int sig)
314 {
315         Sys_PrintfToTerminal("Received signal %d, exiting...\n", sig);
316         VID_RestoreSystemGamma();
317         Sys_Quit(1);
318 }
319
320 void InitSig(void)
321 {
322         signal(SIGHUP, signal_handler);
323         signal(SIGINT, signal_handler);
324         signal(SIGQUIT, signal_handler);
325         signal(SIGILL, signal_handler);
326         signal(SIGTRAP, signal_handler);
327         signal(SIGIOT, signal_handler);
328         signal(SIGBUS, signal_handler);
329         signal(SIGFPE, signal_handler);
330         signal(SIGSEGV, signal_handler);
331         signal(SIGTERM, signal_handler);
332 }
333
334 void VID_Init(void)
335 {
336         InitSig(); // trap evil signals
337         Cvar_RegisterVariable(&apple_multithreadedgl);
338         Cvar_RegisterVariable(&apple_mouse_noaccel);
339 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
340         if (COM_CheckParm ("-nomouse"))
341                 mouse_avail = false;
342 }
343
344 static void *prjobj = NULL;
345 static void *cglobj = NULL;
346
347 static void GL_CloseLibrary(void)
348 {
349         if (cglobj)
350                 dlclose(cglobj);
351         cglobj = NULL;
352         if (prjobj)
353                 dlclose(prjobj);
354         prjobj = NULL;
355         gl_driver[0] = 0;
356         gl_extensions = "";
357         gl_platform = "";
358         gl_platformextensions = "";
359 }
360
361 static int GL_OpenLibrary(void)
362 {
363         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
364         const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
365
366         Con_Printf("Loading OpenGL driver %s\n", name);
367         GL_CloseLibrary();
368         if (!(prjobj = dlopen(name, RTLD_LAZY)))
369         {
370                 Con_Printf("Unable to open symbol list for %s\n", name);
371                 return false;
372         }
373         strlcpy(gl_driver, name, sizeof(gl_driver));
374
375         Con_Printf("Loading OpenGL driver %s\n", name2);
376         if (!(cglobj = dlopen(name2, RTLD_LAZY)))
377                 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
378
379         return true;
380 }
381
382 void *GL_GetProcAddress(const char *name)
383 {
384         return dlsym(prjobj, name);
385 }
386
387 static void *CGL_GetProcAddress(const char *name)
388 {
389         if(!cglobj)
390                 return NULL;
391         return dlsym(cglobj, name);
392 }
393
394 void VID_Shutdown(void)
395 {
396         if (context == NULL && window == NULL)
397                 return;
398
399         VID_EnableJoystick(false);
400         VID_SetMouse(false, false, false);
401         VID_RestoreSystemGamma();
402
403         if (context != NULL)
404         {
405                 qaglDestroyContext(context);
406                 context = NULL;
407         }
408
409         if (vid_isfullscreen)
410                 CGReleaseAllDisplays();
411
412         if (window != NULL)
413         {
414                 DisposeWindow(window);
415                 window = NULL;
416         }
417
418         vid_hidden = true;
419         vid_isfullscreen = false;
420
421         GL_CloseLibrary();
422         Key_ClearStates ();
423 }
424
425 // Since the event handler can be called at any time, we store the events for later processing
426 static qboolean AsyncEvent_Quitting = false;
427 static qboolean AsyncEvent_Collapsed = false;
428 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
429 {
430         OSStatus err = noErr;
431
432         switch (GetEventKind (event))
433         {
434                 case kEventWindowClosed:
435                         AsyncEvent_Quitting = true;
436                         break;
437
438                 // Docked (start)
439                 case kEventWindowCollapsing:
440                         AsyncEvent_Collapsed = true;
441                         break;
442
443                 // Undocked / restored (end)
444                 case kEventWindowExpanded:
445                         AsyncEvent_Collapsed = false;
446                         break;
447
448                 default:
449                         err = eventNotHandledErr;
450                         break;
451         }
452
453         return err;
454 }
455
456 static void VID_AppFocusChanged(qboolean windowIsActive)
457 {
458         if (vid_activewindow != windowIsActive)
459         {
460                 vid_activewindow = windowIsActive;
461                 if (!vid_activewindow)
462                         VID_RestoreSystemGamma();
463         }
464
465         if (windowIsActive || !snd_mutewhenidle.integer)
466         {
467                 if (!sound_active)
468                 {
469                         S_UnblockSound ();
470                         sound_active = true;
471                 }
472         }
473         else
474         {
475                 if (sound_active)
476                 {
477                         S_BlockSound ();
478                         sound_active = false;
479                 }
480         }
481 }
482
483 static void VID_ProcessPendingAsyncEvents (void)
484 {
485         // Collapsed / expanded
486         if (AsyncEvent_Collapsed != vid_hidden)
487         {
488                 vid_hidden = !vid_hidden;
489                 VID_AppFocusChanged(!vid_hidden);
490         }
491
492         // Closed
493         if (AsyncEvent_Quitting)
494                 Sys_Quit(0);
495 }
496
497 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
498 {
499         *attrib++ = AGL_RGBA;
500         *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
501         *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
502         *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
503         *attrib++ = AGL_DOUBLEBUFFER;
504         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
505
506         // if stencil is enabled, ask for alpha too
507         if (stencil)
508         {
509                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
510                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
511         }
512         if (fullscreen)
513                 *attrib++ = AGL_FULLSCREEN;
514         if (stereobuffer)
515                 *attrib++ = AGL_STEREO;
516 #ifdef AGL_SAMPLE_BUFFERS_ARB
517 #ifdef AGL_SAMPLES_ARB
518         if (samples > 1)
519         {
520                 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
521                 *attrib++ = 1;
522                 *attrib++ = AGL_SAMPLES_ARB;
523                 *attrib++ = samples;
524         }
525 #endif
526 #endif
527
528         *attrib++ = AGL_NONE;
529 }
530
531 qboolean VID_InitMode(viddef_mode_t *mode)
532 {
533         const EventTypeSpec winEvents[] =
534         {
535                 { kEventClassWindow, kEventWindowClosed },
536                 { kEventClassWindow, kEventWindowCollapsing },
537                 { kEventClassWindow, kEventWindowExpanded },
538         };
539         OSStatus carbonError;
540         Rect windowBounds;
541         CFStringRef windowTitle;
542         AGLPixelFormat pixelFormat;
543         GLint attributes [32];
544         GLenum error;
545
546         if (!GL_OpenLibrary())
547         {
548                 Con_Printf("Unable to load GL driver\n");
549                 return false;
550         }
551
552         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
553          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
554          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
555          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
556          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
557          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
558          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
559          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
560          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
561          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
562          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
563         )
564         {
565                 Con_Printf("AGL functions not found\n");
566                 ReleaseWindow(window);
567                 return false;
568         }
569
570         qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
571         qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
572         qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
573         if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
574                 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
575
576         // Ignore the events from the previous window
577         AsyncEvent_Quitting = false;
578         AsyncEvent_Collapsed = false;
579
580         // Create the window, a bit towards the center of the screen
581         windowBounds.left = 100;
582         windowBounds.top = 100;
583         windowBounds.right = mode->width + 100;
584         windowBounds.bottom = mode->height + 100;
585         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
586         if (carbonError != noErr || window == NULL)
587         {
588                 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
589                 return false;
590         }
591
592         // Set the window title
593         windowTitle = CFSTR("DarkPlaces AGL");
594         SetWindowTitleWithCFString(window, windowTitle);
595
596         // Install the callback function for the window events we can't get
597         // through ReceiveNextEvent (i.e. close, collapse, and expand)
598         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
599                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
600
601         // Create the desired attribute list
602         VID_BuildAGLAttrib(attributes, mode->bitsperpixel == 32, mode->fullscreen, mode->stereobuffer, mode->samples);
603
604         if (!mode->fullscreen)
605         {
606                 // Output to Window
607                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
608                 error = qaglGetError();
609                 if (error != AGL_NO_ERROR)
610                 {
611                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
612                                         (char *)qaglErrorString(error));
613                         ReleaseWindow(window);
614                         return false;
615                 }
616         }
617         else  // Output is fullScreen
618         {
619                 CGDirectDisplayID mainDisplay;
620                 CFDictionaryRef refDisplayMode;
621                 GDHandle gdhDisplay;
622
623                 // Get the mainDisplay and set resolution to current
624                 mainDisplay = CGMainDisplayID();
625                 CGDisplayCapture(mainDisplay);
626
627                 // TOCHECK: not sure whether or not it's necessary to change the resolution
628                 // "by hand", or if aglSetFullscreen does the job anyway
629                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty(mainDisplay, mode->bitsperpixel, mode->width, mode->height, mode->refreshrate, kCGDisplayModeIsSafeForHardware, NULL);
630                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
631                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
632
633                 // Set pixel format with built attribs
634                 // Note: specifying a device is *required* for AGL_FullScreen
635                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
636                 error = qaglGetError();
637                 if (error != AGL_NO_ERROR)
638                 {
639                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
640                                                 (char *)qaglErrorString(error));
641                         ReleaseWindow(window);
642                         return false;
643                 }
644         }
645
646         // Create a context using the pform
647         context = qaglCreateContext(pixelFormat, NULL);
648         error = qaglGetError();
649         if (error != AGL_NO_ERROR)
650         {
651                 Con_Printf("qaglCreateContext FAILED: %s\n",
652                                         (char *)qaglErrorString(error));
653         }
654
655         // Make the context the current one ('enable' it)
656         qaglSetCurrentContext(context);
657         error = qaglGetError();
658         if (error != AGL_NO_ERROR)
659         {
660                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
661                                         (char *)qaglErrorString(error));
662                 ReleaseWindow(window);
663                 return false;
664         }
665
666         // Discard pform
667         qaglDestroyPixelFormat(pixelFormat);
668
669         // Attempt fullscreen if requested
670         if (mode->fullscreen)
671         {
672                 qaglSetFullScreen (context, mode->width, mode->height, mode->refreshrate, 0);
673                 error = qaglGetError();
674                 if (error != AGL_NO_ERROR)
675                 {
676                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
677                                                 (char *)qaglErrorString(error));
678                         return false;
679                 }
680         }
681         else
682         {
683                 // Set Window as Drawable
684                 qaglSetDrawable(context, GetWindowPort(window));
685                 error = qaglGetError();
686                 if (error != AGL_NO_ERROR)
687                 {
688                         Con_Printf("qaglSetDrawable FAILED: %s\n",
689                                                 (char *)qaglErrorString(error));
690                         ReleaseWindow(window);
691                         return false;
692                 }
693         }
694
695         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
696                 Sys_Error("glGetString not found in %s", gl_driver);
697
698         gl_platformextensions = "";
699         gl_platform = "AGL";
700
701         multithreadedgl = false;
702         vid_isfullscreen = mode->fullscreen;
703         vid_usingmouse = false;
704         vid_usinghidecursor = false;
705         vid_hidden = false;
706         vid_activewindow = true;
707         sound_active = true;
708         GL_Init();
709
710         SelectWindow(window);
711         ShowWindow(window);
712
713         return true;
714 }
715
716 static void Handle_KeyMod(UInt32 keymod)
717 {
718         const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
719         {
720                 { cmdKey,                                               K_AUX1 },
721                 { shiftKey,                                             K_SHIFT },
722                 { alphaLock,                                    K_CAPSLOCK },
723                 { optionKey,                                    K_ALT },
724                 { controlKey,                                   K_CTRL },
725                 { kEventKeyModifierNumLockMask, K_NUMLOCK },
726                 { kEventKeyModifierFnMask,              K_AUX2 }
727         };
728         static UInt32 prev_keymod = 0;
729         unsigned int i;
730         UInt32 modChanges;
731
732         modChanges = prev_keymod ^ keymod;
733         if (modChanges == 0)
734                 return;
735
736         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
737         {
738                 UInt32 keybit = keymod_events[i].keybit;
739
740                 if ((modChanges & keybit) != 0)
741                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
742         }
743
744         prev_keymod = keymod;
745 }
746
747 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
748 {
749         unsigned int keycode = 0;
750         char ascii = '\0';
751
752         switch (mackeycode)
753         {
754                 case MK_ESCAPE:
755                         keycode = K_ESCAPE;
756                         break;
757                 case MK_F1:
758                         keycode = K_F1;
759                         break;
760                 case MK_F2:
761                         keycode = K_F2;
762                         break;
763                 case MK_F3:
764                         keycode = K_F3;
765                         break;
766                 case MK_F4:
767                         keycode = K_F4;
768                         break;
769                 case MK_F5:
770                         keycode = K_F5;
771                         break;
772                 case MK_F6:
773                         keycode = K_F6;
774                         break;
775                 case MK_F7:
776                         keycode = K_F7;
777                         break;
778                 case MK_F8:
779                         keycode = K_F8;
780                         break;
781                 case MK_F9:
782                         keycode = K_F9;
783                         break;
784                 case MK_F10:
785                         keycode = K_F10;
786                         break;
787                 case MK_F11:
788                         keycode = K_F11;
789                         break;
790                 case MK_F12:
791                         keycode = K_F12;
792                         break;
793                 case MK_SCROLLOCK:
794                         keycode = K_SCROLLOCK;
795                         break;
796                 case MK_PAUSE:
797                         keycode = K_PAUSE;
798                         break;
799                 case MK_BACKSPACE:
800                         keycode = K_BACKSPACE;
801                         break;
802                 case MK_INSERT:
803                         keycode = K_INS;
804                         break;
805                 case MK_HOME:
806                         keycode = K_HOME;
807                         break;
808                 case MK_PAGEUP:
809                         keycode = K_PGUP;
810                         break;
811                 case MK_NUMLOCK:
812                         keycode = K_NUMLOCK;
813                         break;
814                 case MK_KP_EQUALS:
815                         keycode = K_KP_EQUALS;
816                         break;
817                 case MK_KP_DIVIDE:
818                         keycode = K_KP_DIVIDE;
819                         break;
820                 case MK_KP_MULTIPLY:
821                         keycode = K_KP_MULTIPLY;
822                         break;
823                 case MK_TAB:
824                         keycode = K_TAB;
825                         break;
826                 case MK_DELETE:
827                         keycode = K_DEL;
828                         break;
829                 case MK_END:
830                         keycode = K_END;
831                         break;
832                 case MK_PAGEDOWN:
833                         keycode = K_PGDN;
834                         break;
835                 case MK_KP7:
836                         keycode = K_KP_7;
837                         break;
838                 case MK_KP8:
839                         keycode = K_KP_8;
840                         break;
841                 case MK_KP9:
842                         keycode = K_KP_9;
843                         break;
844                 case MK_KP_MINUS:
845                         keycode = K_KP_MINUS;
846                         break;
847                 case MK_CAPSLOCK:
848                         keycode = K_CAPSLOCK;
849                         break;
850                 case MK_RETURN:
851                         keycode = K_ENTER;
852                         break;
853                 case MK_KP4:
854                         keycode = K_KP_4;
855                         break;
856                 case MK_KP5:
857                         keycode = K_KP_5;
858                         break;
859                 case MK_KP6:
860                         keycode = K_KP_6;
861                         break;
862                 case MK_KP_PLUS:
863                         keycode = K_KP_PLUS;
864                         break;
865                 case MK_KP1:
866                         keycode = K_KP_1;
867                         break;
868                 case MK_KP2:
869                         keycode = K_KP_2;
870                         break;
871                 case MK_KP3:
872                         keycode = K_KP_3;
873                         break;
874                 case MK_KP_ENTER:
875                 case MK_IBOOK_ENTER:
876                         keycode = K_KP_ENTER;
877                         break;
878                 case MK_KP0:
879                         keycode = K_KP_0;
880                         break;
881                 case MK_KP_PERIOD:
882                         keycode = K_KP_PERIOD;
883                         break;
884                 default:
885                         switch(charcode)
886                         {
887                                 case kUpArrowCharCode:
888                                         keycode = K_UPARROW;
889                                         break;
890                                 case kLeftArrowCharCode:
891                                         keycode = K_LEFTARROW;
892                                         break;
893                                 case kDownArrowCharCode:
894                                         keycode = K_DOWNARROW;
895                                         break;
896                                 case kRightArrowCharCode:
897                                         keycode = K_RIGHTARROW;
898                                         break;
899                                 case 0:
900                                 case 191:
901                                         // characters 0 and 191 are sent by the mouse buttons (?!)
902                                         break;
903                                 default:
904                                         if ('A' <= charcode && charcode <= 'Z')
905                                         {
906                                                 keycode = charcode + ('a' - 'A');  // lowercase it
907                                                 ascii = charcode;
908                                         }
909                                         else if (charcode >= 32)
910                                         {
911                                                 keycode = charcode;
912                                                 ascii = charcode;
913                                         }
914                                         else
915                                                 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
916                         }
917         }
918
919         if (keycode != 0)
920                 Key_Event(keycode, ascii, keypressed);
921 }
922
923 void Sys_SendKeyEvents(void)
924 {
925         EventRef theEvent;
926         EventTargetRef theTarget;
927
928         // Start by processing the asynchronous events we received since the previous frame
929         VID_ProcessPendingAsyncEvents();
930
931         theTarget = GetEventDispatcherTarget();
932         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
933         {
934                 UInt32 eventClass = GetEventClass(theEvent);
935                 UInt32 eventKind = GetEventKind(theEvent);
936
937                 switch (eventClass)
938                 {
939                         case kEventClassMouse:
940                         {
941                                 EventMouseButton theButton;
942                                 int key;
943
944                                 switch (eventKind)
945                                 {
946                                         case kEventMouseDown:
947                                         case kEventMouseUp:
948                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
949                                                 switch (theButton)
950                                                 {
951                                                         default:
952                                                         case kEventMouseButtonPrimary:
953                                                                 key = K_MOUSE1;
954                                                                 break;
955                                                         case kEventMouseButtonSecondary:
956                                                                 key = K_MOUSE2;
957                                                                 break;
958                                                         case kEventMouseButtonTertiary:
959                                                                 key = K_MOUSE3;
960                                                                 break;
961                                                 }
962                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
963                                                 break;
964
965                                         // Note: These two events are mutual exclusives
966                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
967                                         case kEventMouseMoved:
968                                         case kEventMouseDragged:
969                                         {
970                                                 HIPoint deltaPos;
971                                                 HIPoint windowPos;
972
973                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
974                                                 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
975
976                                                 if (vid_usingmouse)
977                                                 {
978                                                         in_mouse_x += deltaPos.x;
979                                                         in_mouse_y += deltaPos.y;
980                                                 }
981
982                                                 in_windowmouse_x = windowPos.x;
983                                                 in_windowmouse_y = windowPos.y;
984                                                 break;
985                                         }
986
987                                         case kEventMouseWheelMoved:
988                                         {
989                                                 SInt32 delta;
990                                                 unsigned int wheelEvent;
991
992                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
993
994                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
995                                                 Key_Event(wheelEvent, 0, true);
996                                                 Key_Event(wheelEvent, 0, false);
997                                                 break;
998                                         }
999
1000                                         default:
1001                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1002                                                 break;
1003                                 }
1004                         }
1005
1006                         case kEventClassKeyboard:
1007                         {
1008                                 char charcode;
1009                                 UInt32 keycode;
1010
1011                                 switch (eventKind)
1012                                 {
1013                                         case kEventRawKeyDown:
1014                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1015                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1016                                                 Handle_Key(charcode, keycode, true);
1017                                                 break;
1018
1019                                         case kEventRawKeyRepeat:
1020                                                 break;
1021
1022                                         case kEventRawKeyUp:
1023                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1024                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1025                                                 Handle_Key(charcode, keycode, false);
1026                                                 break;
1027
1028                                         case kEventRawKeyModifiersChanged:
1029                                         {
1030                                                 UInt32 keymod = 0;
1031                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1032                                                 Handle_KeyMod(keymod);
1033                                                 break;
1034                                         }
1035
1036                                         case kEventHotKeyPressed:
1037                                                 break;
1038
1039                                         case kEventHotKeyReleased:
1040                                                 break;
1041
1042                                         case kEventMouseWheelMoved:
1043                                                 break;
1044
1045                                         default:
1046                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1047                                                 break;
1048                                 }
1049                                 break;
1050                         }
1051
1052                         case kEventClassTextInput:
1053                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1054                                 break;
1055
1056                         case kEventClassApplication:
1057                                 switch (eventKind)
1058                                 {
1059                                         case kEventAppActivated :
1060                                                 VID_AppFocusChanged(true);
1061                                                 break;
1062                                         case kEventAppDeactivated:
1063                                                 VID_AppFocusChanged(false);
1064                                                 break;
1065                                         case kEventAppQuit:
1066                                                 Sys_Quit(0);
1067                                                 break;
1068                                         case kEventAppActiveWindowChanged:
1069                                                 break;
1070                                         default:
1071                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1072                                                 break;
1073                                 }
1074                                 break;
1075
1076                         case kEventClassAppleEvent:
1077                                 switch (eventKind)
1078                                 {
1079                                         case kEventAppleEvent :
1080                                                 break;
1081                                         default:
1082                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1083                                                 break;
1084                                 }
1085                                 break;
1086
1087                         case kEventClassWindow:
1088                                 switch (eventKind)
1089                                 {
1090                                         case kEventWindowUpdate :
1091                                                 break;
1092                                         default:
1093                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1094                                                 break;
1095                                 }
1096                                 break;
1097
1098                         case kEventClassControl:
1099                                 break;
1100
1101                         default:
1102                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1103                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
1104                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1105                                                         eventKind);*/
1106                                 break;
1107                 }
1108
1109                 SendEventToEventTarget (theEvent, theTarget);
1110                 ReleaseEvent(theEvent);
1111         }
1112 }
1113
1114 void VID_BuildJoyState(vid_joystate_t *joystate)
1115 {
1116         VID_Shared_BuildJoyState_Begin(joystate);
1117         VID_Shared_BuildJoyState_Finish(joystate);
1118 }
1119
1120 void VID_EnableJoystick(qboolean enable)
1121 {
1122         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1123         qboolean success = false;
1124         int sharedcount = 0;
1125         sharedcount = VID_Shared_SetJoystick(index);
1126         if (index >= 0 && index < sharedcount)
1127                 success = true;
1128
1129         // update cvar containing count of XInput joysticks
1130         if (joy_detected.integer != sharedcount)
1131                 Cvar_SetValueQuick(&joy_detected, sharedcount);
1132
1133         Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1134 }
1135
1136 void IN_Move (void)
1137 {
1138         vid_joystate_t joystate;
1139         VID_EnableJoystick(true);
1140         VID_BuildJoyState(&joystate);
1141         VID_ApplyJoyState(&joystate);
1142 }
1143
1144 static bool GetDictionaryBoolean(CFDictionaryRef d, const void *key)
1145 {
1146     CFBooleanRef ref = (CFBooleanRef) CFDictionaryGetValue(d, key);
1147     if(ref)
1148         return CFBooleanGetValue(ref);
1149     return false;
1150 }
1151
1152 long GetDictionaryLong(CFDictionaryRef d, const void *key)
1153 {
1154         long value = 0;
1155     CFNumberRef ref = (CFNumberRef) CFDictionaryGetValue(d, key);
1156     if(ref)
1157         CFNumberGetValue(ref, kCFNumberLongType, &value);
1158     return value;
1159 }
1160
1161 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1162 {
1163         CGDirectDisplayID mainDisplay = CGMainDisplayID();
1164         CFArrayRef vidmodes = CGDisplayAvailableModes(mainDisplay);
1165         CFDictionaryRef thismode;
1166         unsigned int n = CFArrayGetCount(vidmodes);
1167         unsigned int i;
1168         size_t k;
1169
1170         k = 0;
1171         for(i = 0; i < n; ++i)
1172         {
1173                 thismode = (CFDictionaryRef) CFArrayGetValueAtIndex(vidmodes, i);
1174                 if(!GetDictionaryBoolean(thismode, kCGDisplayModeIsSafeForHardware))
1175                         continue;
1176
1177                 if(k >= maxcount)
1178                         break;
1179                 modes[k].width = GetDictionaryLong(thismode, kCGDisplayWidth);
1180                 modes[k].height = GetDictionaryLong(thismode, kCGDisplayHeight);
1181                 modes[k].bpp = GetDictionaryLong(thismode, kCGDisplayBitsPerPixel);
1182                 modes[k].refreshrate = GetDictionaryLong(thismode, kCGDisplayRefreshRate);
1183                 modes[k].pixelheight_num = 1;
1184                 modes[k].pixelheight_denom = 1; // OS X doesn't expose this either
1185                 ++k;
1186         }
1187         return k;
1188 }