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