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