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