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