4 Mac OS X OpenGL and input module, using Carbon and AGL
6 Copyright (C) 2005-2006 Mathieu Olivier
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.
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.
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
27 #include <Carbon/Carbon.h>
31 // Tell startup code that we have a client
32 int cl_available = true;
34 qboolean vid_supportrefreshrate = true;
37 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
38 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
39 GLboolean (*qaglDestroyContext) (AGLContext ctx);
40 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
41 const GLubyte* (*qaglErrorString) (GLenum code);
42 GLenum (*qaglGetError) (void);
43 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
44 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
45 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
46 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
47 void (*qaglSwapBuffers) (AGLContext ctx);
49 static qboolean mouse_avail = true;
50 static qboolean vid_usingmouse = false;
51 static float mouse_x, mouse_y;
53 static qboolean vid_isfullscreen = false;
54 static qboolean vid_usingvsync = false;
56 static qboolean sound_active = true;
58 static int scr_width, scr_height;
60 static AGLContext context;
61 static WindowRef window;
64 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
71 static void IN_Activate( qboolean grab )
75 if (!vid_usingmouse && mouse_avail && window)
81 CGDisplayHideCursor(CGMainDisplayID());
83 // Put the mouse cursor at the center of the window
84 GetWindowBounds (window, kWindowContentRgn, &winBounds);
85 winCenter.x = (winBounds.left + winBounds.right) / 2;
86 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
87 CGWarpMouseCursorPosition(winCenter);
89 // Lock the mouse pointer at its current position
90 CGAssociateMouseAndMouseCursorPosition(false);
92 mouse_x = mouse_y = 0;
93 vid_usingmouse = true;
100 CGAssociateMouseAndMouseCursorPosition(true);
101 CGDisplayShowCursor(CGMainDisplayID());
103 vid_usingmouse = false;
108 #define GAMMA_TABLE_SIZE 256
109 void VID_Finish (qboolean allowmousegrab)
111 qboolean vid_usemouse;
112 qboolean vid_usevsync;
114 // handle the mouse state when windowed if that's changed
115 vid_usemouse = false;
116 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
118 if (!vid_activewindow)
119 vid_usemouse = false;
120 if (vid_isfullscreen)
122 IN_Activate(vid_usemouse);
124 // handle changes of the vsync option
125 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
126 if (vid_usingvsync != vid_usevsync)
128 GLint sync = (vid_usevsync ? 1 : 0);
130 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
132 vid_usingvsync = vid_usevsync;
133 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
136 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
139 if (r_render.integer)
142 if (r_speeds.integer || gl_finish.integer)
144 qglFinish();CHECKGLERROR
146 qaglSwapBuffers(context);
148 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
151 int VID_SetGamma(unsigned short *ramps, int rampsize)
153 CGGammaValue table_red [GAMMA_TABLE_SIZE];
154 CGGammaValue table_green [GAMMA_TABLE_SIZE];
155 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
158 // Convert the unsigned short table into 3 float tables
159 for (i = 0; i < rampsize; i++)
160 table_red[i] = (float)ramps[i] / 65535.0f;
161 for (i = 0; i < rampsize; i++)
162 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
163 for (i = 0; i < rampsize; i++)
164 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
166 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
168 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
175 int VID_GetGamma(unsigned short *ramps, int rampsize)
177 CGGammaValue table_red [GAMMA_TABLE_SIZE];
178 CGGammaValue table_green [GAMMA_TABLE_SIZE];
179 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
180 CGTableCount actualsize = 0;
183 // Get the gamma ramps from the system
184 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
186 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
189 if (actualsize != (unsigned int)rampsize)
191 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
195 // Convert the 3 float tables into 1 unsigned short table
196 for (i = 0; i < rampsize; i++)
197 ramps[i] = table_red[i] * 65535.0f;
198 for (i = 0; i < rampsize; i++)
199 ramps[i + rampsize] = table_green[i] * 65535.0f;
200 for (i = 0; i < rampsize; i++)
201 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
206 void signal_handler(int sig)
208 printf("Received signal %d, exiting...\n", sig);
209 VID_RestoreSystemGamma();
216 signal(SIGHUP, signal_handler);
217 signal(SIGINT, signal_handler);
218 signal(SIGQUIT, signal_handler);
219 signal(SIGILL, signal_handler);
220 signal(SIGTRAP, signal_handler);
221 signal(SIGIOT, signal_handler);
222 signal(SIGBUS, signal_handler);
223 signal(SIGFPE, signal_handler);
224 signal(SIGSEGV, signal_handler);
225 signal(SIGTERM, signal_handler);
230 InitSig(); // trap evil signals
231 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
232 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
236 static void *prjobj = NULL;
238 static void GL_CloseLibrary(void)
246 gl_platformextensions = "";
249 static int GL_OpenLibrary(void)
251 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
253 Con_Printf("Loading OpenGL driver %s\n", name);
255 if (!(prjobj = dlopen(name, RTLD_LAZY)))
257 Con_Printf("Unable to open symbol list for %s\n", name);
260 strlcpy(gl_driver, name, sizeof(gl_driver));
264 void *GL_GetProcAddress(const char *name)
266 return dlsym(prjobj, name);
269 void VID_Shutdown(void)
271 if (context == NULL && window == NULL)
275 VID_RestoreSystemGamma();
279 qaglDestroyContext(context);
283 if (vid_isfullscreen)
284 CGReleaseAllDisplays();
288 DisposeWindow(window);
293 vid_isfullscreen = false;
299 // Since the event handler can be called at any time, we store the events for later processing
300 static qboolean AsyncEvent_Quitting = false;
301 static qboolean AsyncEvent_Collapsed = false;
302 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
304 OSStatus err = noErr;
306 switch (GetEventKind (event))
308 case kEventWindowClosed:
309 AsyncEvent_Quitting = true;
313 case kEventWindowCollapsing:
314 AsyncEvent_Collapsed = true;
317 // Undocked / restored (end)
318 case kEventWindowExpanded:
319 AsyncEvent_Collapsed = false;
323 err = eventNotHandledErr;
330 static void VID_AppFocusChanged(qboolean windowIsActive)
332 if (vid_activewindow != windowIsActive)
334 vid_activewindow = windowIsActive;
335 if (!vid_activewindow)
336 VID_RestoreSystemGamma();
339 if (sound_active != windowIsActive)
341 sound_active = windowIsActive;
349 static void VID_ProcessPendingAsyncEvents (void)
351 // Collapsed / expanded
352 if (AsyncEvent_Collapsed != vid_hidden)
354 vid_hidden = !vid_hidden;
355 VID_AppFocusChanged(!vid_hidden);
359 if (AsyncEvent_Quitting)
363 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen)
365 *attrib++ = AGL_RGBA;
366 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
367 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
368 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
369 *attrib++ = AGL_DOUBLEBUFFER;
370 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
372 // if stencil is enabled, ask for alpha too
375 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
376 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
379 *attrib++ = AGL_FULLSCREEN;
380 *attrib++ = AGL_NONE;
383 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
385 const EventTypeSpec winEvents[] =
387 { kEventClassWindow, kEventWindowClosed },
388 { kEventClassWindow, kEventWindowCollapsing },
389 { kEventClassWindow, kEventWindowExpanded },
391 OSStatus carbonError;
393 CFStringRef windowTitle;
394 AGLPixelFormat pixelFormat;
395 GLint attributes [32];
398 if (!GL_OpenLibrary())
400 Con_Printf("Unable to load GL driver\n");
404 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
405 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
406 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
407 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
408 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
409 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
410 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
411 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
412 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
413 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
414 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
417 Con_Printf("AGL functions not found\n");
418 ReleaseWindow(window);
422 // Ignore the events from the previous window
423 AsyncEvent_Quitting = false;
424 AsyncEvent_Collapsed = false;
426 // Create the window, a bit towards the center of the screen
427 windowBounds.left = 100;
428 windowBounds.top = 100;
429 windowBounds.right = width + 100;
430 windowBounds.bottom = height + 100;
431 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
432 if (carbonError != noErr || window == NULL)
434 Con_Printf("Unable to create window (error %d)\n", carbonError);
438 // Set the window title
439 windowTitle = CFSTR("DarkPlaces AGL");
440 SetWindowTitleWithCFString(window, windowTitle);
442 // Install the callback function for the window events we can't get
443 // through ReceiveNextEvent (i.e. close, collapse, and expand)
444 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
445 GetEventTypeCount(winEvents), winEvents, window, NULL);
447 // Create the desired attribute list
448 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
453 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
454 error = qaglGetError();
455 if (error != AGL_NO_ERROR)
457 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
458 (char *)qaglErrorString(error));
459 ReleaseWindow(window);
463 else // Output is fullScreen
465 CGDirectDisplayID mainDisplay;
466 CFDictionaryRef refDisplayMode;
469 // Get the mainDisplay and set resolution to current
470 mainDisplay = CGMainDisplayID();
471 CGDisplayCapture(mainDisplay);
473 // TOCHECK: not sure whether or not it's necessary to change the resolution
474 // "by hand", or if aglSetFullscreen does the job anyway
475 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
476 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
477 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
479 // Set pixel format with built attribs
480 // Note: specifying a device is *required* for AGL_FullScreen
481 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
482 error = qaglGetError();
483 if (error != AGL_NO_ERROR)
485 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
486 (char *)qaglErrorString(error));
487 ReleaseWindow(window);
492 // Create a context using the pform
493 context = qaglCreateContext(pixelFormat, NULL);
494 error = qaglGetError();
495 if (error != AGL_NO_ERROR)
497 Con_Printf("qaglCreateContext FAILED: %s\n",
498 (char *)qaglErrorString(error));
501 // Make the context the current one ('enable' it)
502 qaglSetCurrentContext(context);
503 error = qaglGetError();
504 if (error != AGL_NO_ERROR)
506 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
507 (char *)qaglErrorString(error));
508 ReleaseWindow(window);
513 qaglDestroyPixelFormat(pixelFormat);
515 // Attempt fullscreen if requested
518 qaglSetFullScreen (context, width, height, refreshrate, 0);
519 error = qaglGetError();
520 if (error != AGL_NO_ERROR)
522 Con_Printf("qaglSetFullScreen FAILED: %s\n",
523 (char *)qaglErrorString(error));
529 // Set Window as Drawable
530 qaglSetDrawable(context, GetWindowPort(window));
531 error = qaglGetError();
532 if (error != AGL_NO_ERROR)
534 Con_Printf("qaglSetDrawable FAILED: %s\n",
535 (char *)qaglErrorString(error));
536 ReleaseWindow(window);
544 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
545 Sys_Error("glGetString not found in %s", gl_driver);
547 gl_renderer = (const char *)qglGetString(GL_RENDERER);
548 gl_vendor = (const char *)qglGetString(GL_VENDOR);
549 gl_version = (const char *)qglGetString(GL_VERSION);
550 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
552 gl_videosyncavailable = true;
554 vid_isfullscreen = fullscreen;
555 vid_usingmouse = false;
557 vid_activewindow = true;
561 SelectWindow(window);
567 static void Handle_KeyMod(UInt32 keymod)
569 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
572 { shiftKey, K_SHIFT },
573 { alphaLock, K_CAPSLOCK },
574 { optionKey, K_ALT },
575 { controlKey, K_CTRL },
576 { kEventKeyModifierNumLockMask, K_NUMLOCK },
577 { kEventKeyModifierFnMask, K_AUX2 }
579 static UInt32 prev_keymod = 0;
583 modChanges = prev_keymod ^ keymod;
587 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
589 UInt32 keybit = keymod_events[i].keybit;
591 if ((modChanges & keybit) != 0)
592 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
595 prev_keymod = keymod;
598 static void Handle_Key(unsigned char charcode, qboolean keypressed)
600 unsigned int keycode = 0;
609 keycode = K_KP_ENTER;
614 case kBackspaceCharCode:
615 keycode = K_BACKSPACE;
620 case kPageUpCharCode:
623 case kPageDownCharCode:
626 case kReturnCharCode:
629 case kEscapeCharCode:
632 case kLeftArrowCharCode:
633 keycode = K_LEFTARROW;
635 case kRightArrowCharCode:
636 keycode = K_RIGHTARROW;
638 case kUpArrowCharCode:
641 case kDownArrowCharCode :
642 keycode = K_DOWNARROW;
644 case kDeleteCharCode:
649 // characters 0 and 191 are sent by the mouse buttons (?!)
652 if ('A' <= charcode && charcode <= 'Z')
654 keycode = charcode + ('a' - 'A'); // lowercase it
657 else if (charcode >= 32)
663 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
667 Key_Event(keycode, ascii, keypressed);
670 void Sys_SendKeyEvents(void)
673 EventTargetRef theTarget;
675 // Start by processing the asynchronous events we received since the previous frame
676 VID_ProcessPendingAsyncEvents();
678 theTarget = GetEventDispatcherTarget();
679 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
681 UInt32 eventClass = GetEventClass(theEvent);
682 UInt32 eventKind = GetEventKind(theEvent);
686 case kEventClassMouse:
688 EventMouseButton theButton;
693 case kEventMouseDown:
695 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
699 case kEventMouseButtonPrimary:
702 case kEventMouseButtonSecondary:
705 case kEventMouseButtonTertiary:
709 Key_Event(key, '\0', eventKind == kEventMouseDown);
712 // Note: These two events are mutual exclusives
713 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
714 case kEventMouseMoved:
715 case kEventMouseDragged:
719 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
721 mouse_x += deltaPos.x;
722 mouse_y += deltaPos.y;
726 case kEventMouseWheelMoved:
729 unsigned int wheelEvent;
731 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
733 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
734 Key_Event(wheelEvent, 0, true);
735 Key_Event(wheelEvent, 0, false);
740 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
745 case kEventClassKeyboard:
751 case kEventRawKeyDown:
752 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
753 Handle_Key(keycode, true);
756 case kEventRawKeyRepeat:
760 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
761 Handle_Key(keycode, false);
764 case kEventRawKeyModifiersChanged:
767 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
768 Handle_KeyMod(keymod);
772 case kEventHotKeyPressed:
775 case kEventHotKeyReleased:
778 case kEventMouseWheelMoved:
782 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
788 case kEventClassTextInput:
789 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
792 case kEventClassApplication:
795 case kEventAppActivated :
796 VID_AppFocusChanged(true);
798 case kEventAppDeactivated:
799 VID_AppFocusChanged(false);
804 case kEventAppActiveWindowChanged:
807 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
812 case kEventClassAppleEvent:
815 case kEventAppleEvent :
818 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
823 case kEventClassWindow:
826 case kEventWindowUpdate :
829 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
834 case kEventClassControl:
838 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
839 eventClass >> 24, (eventClass >> 16) & 0xFF,
840 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
845 SendEventToEventTarget (theEvent, theTarget);
846 ReleaseEvent(theEvent);
854 in_mouse_x = mouse_x;
855 in_mouse_y = mouse_y;