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, qboolean stereobuffer)
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;
381 *attrib++ = AGL_STEREO;
382 *attrib++ = AGL_NONE;
385 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
387 const EventTypeSpec winEvents[] =
389 { kEventClassWindow, kEventWindowClosed },
390 { kEventClassWindow, kEventWindowCollapsing },
391 { kEventClassWindow, kEventWindowExpanded },
393 OSStatus carbonError;
395 CFStringRef windowTitle;
396 AGLPixelFormat pixelFormat;
397 GLint attributes [32];
400 if (!GL_OpenLibrary())
402 Con_Printf("Unable to load GL driver\n");
406 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
407 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
408 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
409 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
410 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
411 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
412 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
413 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
414 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
415 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
416 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
419 Con_Printf("AGL functions not found\n");
420 ReleaseWindow(window);
424 // Ignore the events from the previous window
425 AsyncEvent_Quitting = false;
426 AsyncEvent_Collapsed = false;
428 // Create the window, a bit towards the center of the screen
429 windowBounds.left = 100;
430 windowBounds.top = 100;
431 windowBounds.right = width + 100;
432 windowBounds.bottom = height + 100;
433 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
434 if (carbonError != noErr || window == NULL)
436 Con_Printf("Unable to create window (error %d)\n", carbonError);
440 // Set the window title
441 windowTitle = CFSTR("DarkPlaces AGL");
442 SetWindowTitleWithCFString(window, windowTitle);
444 // Install the callback function for the window events we can't get
445 // through ReceiveNextEvent (i.e. close, collapse, and expand)
446 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
447 GetEventTypeCount(winEvents), winEvents, window, NULL);
449 // Create the desired attribute list
450 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer);
455 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
456 error = qaglGetError();
457 if (error != AGL_NO_ERROR)
459 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
460 (char *)qaglErrorString(error));
461 ReleaseWindow(window);
465 else // Output is fullScreen
467 CGDirectDisplayID mainDisplay;
468 CFDictionaryRef refDisplayMode;
471 // Get the mainDisplay and set resolution to current
472 mainDisplay = CGMainDisplayID();
473 CGDisplayCapture(mainDisplay);
475 // TOCHECK: not sure whether or not it's necessary to change the resolution
476 // "by hand", or if aglSetFullscreen does the job anyway
477 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
478 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
479 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
481 // Set pixel format with built attribs
482 // Note: specifying a device is *required* for AGL_FullScreen
483 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
484 error = qaglGetError();
485 if (error != AGL_NO_ERROR)
487 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
488 (char *)qaglErrorString(error));
489 ReleaseWindow(window);
494 // Create a context using the pform
495 context = qaglCreateContext(pixelFormat, NULL);
496 error = qaglGetError();
497 if (error != AGL_NO_ERROR)
499 Con_Printf("qaglCreateContext FAILED: %s\n",
500 (char *)qaglErrorString(error));
503 // Make the context the current one ('enable' it)
504 qaglSetCurrentContext(context);
505 error = qaglGetError();
506 if (error != AGL_NO_ERROR)
508 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
509 (char *)qaglErrorString(error));
510 ReleaseWindow(window);
515 qaglDestroyPixelFormat(pixelFormat);
517 // Attempt fullscreen if requested
520 qaglSetFullScreen (context, width, height, refreshrate, 0);
521 error = qaglGetError();
522 if (error != AGL_NO_ERROR)
524 Con_Printf("qaglSetFullScreen FAILED: %s\n",
525 (char *)qaglErrorString(error));
531 // Set Window as Drawable
532 qaglSetDrawable(context, GetWindowPort(window));
533 error = qaglGetError();
534 if (error != AGL_NO_ERROR)
536 Con_Printf("qaglSetDrawable FAILED: %s\n",
537 (char *)qaglErrorString(error));
538 ReleaseWindow(window);
546 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
547 Sys_Error("glGetString not found in %s", gl_driver);
549 gl_renderer = (const char *)qglGetString(GL_RENDERER);
550 gl_vendor = (const char *)qglGetString(GL_VENDOR);
551 gl_version = (const char *)qglGetString(GL_VERSION);
552 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
554 gl_videosyncavailable = true;
556 vid_isfullscreen = fullscreen;
557 vid_usingmouse = false;
559 vid_activewindow = true;
563 SelectWindow(window);
569 static void Handle_KeyMod(UInt32 keymod)
571 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
574 { shiftKey, K_SHIFT },
575 { alphaLock, K_CAPSLOCK },
576 { optionKey, K_ALT },
577 { controlKey, K_CTRL },
578 { kEventKeyModifierNumLockMask, K_NUMLOCK },
579 { kEventKeyModifierFnMask, K_AUX2 }
581 static UInt32 prev_keymod = 0;
585 modChanges = prev_keymod ^ keymod;
589 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
591 UInt32 keybit = keymod_events[i].keybit;
593 if ((modChanges & keybit) != 0)
594 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
597 prev_keymod = keymod;
600 static void Handle_Key(unsigned char charcode, qboolean keypressed)
602 unsigned int keycode = 0;
611 keycode = K_KP_ENTER;
616 case kBackspaceCharCode:
617 keycode = K_BACKSPACE;
622 case kPageUpCharCode:
625 case kPageDownCharCode:
628 case kReturnCharCode:
631 case kEscapeCharCode:
634 case kLeftArrowCharCode:
635 keycode = K_LEFTARROW;
637 case kRightArrowCharCode:
638 keycode = K_RIGHTARROW;
640 case kUpArrowCharCode:
643 case kDownArrowCharCode :
644 keycode = K_DOWNARROW;
646 case kDeleteCharCode:
651 // characters 0 and 191 are sent by the mouse buttons (?!)
654 if ('A' <= charcode && charcode <= 'Z')
656 keycode = charcode + ('a' - 'A'); // lowercase it
659 else if (charcode >= 32)
665 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
669 Key_Event(keycode, ascii, keypressed);
672 void Sys_SendKeyEvents(void)
675 EventTargetRef theTarget;
677 // Start by processing the asynchronous events we received since the previous frame
678 VID_ProcessPendingAsyncEvents();
680 theTarget = GetEventDispatcherTarget();
681 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
683 UInt32 eventClass = GetEventClass(theEvent);
684 UInt32 eventKind = GetEventKind(theEvent);
688 case kEventClassMouse:
690 EventMouseButton theButton;
695 case kEventMouseDown:
697 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
701 case kEventMouseButtonPrimary:
704 case kEventMouseButtonSecondary:
707 case kEventMouseButtonTertiary:
711 Key_Event(key, '\0', eventKind == kEventMouseDown);
714 // Note: These two events are mutual exclusives
715 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
716 case kEventMouseMoved:
717 case kEventMouseDragged:
721 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
723 mouse_x += deltaPos.x;
724 mouse_y += deltaPos.y;
728 case kEventMouseWheelMoved:
731 unsigned int wheelEvent;
733 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
735 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
736 Key_Event(wheelEvent, 0, true);
737 Key_Event(wheelEvent, 0, false);
742 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
747 case kEventClassKeyboard:
753 case kEventRawKeyDown:
754 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
755 Handle_Key(keycode, true);
758 case kEventRawKeyRepeat:
762 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
763 Handle_Key(keycode, false);
766 case kEventRawKeyModifiersChanged:
769 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
770 Handle_KeyMod(keymod);
774 case kEventHotKeyPressed:
777 case kEventHotKeyReleased:
780 case kEventMouseWheelMoved:
784 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
790 case kEventClassTextInput:
791 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
794 case kEventClassApplication:
797 case kEventAppActivated :
798 VID_AppFocusChanged(true);
800 case kEventAppDeactivated:
801 VID_AppFocusChanged(false);
806 case kEventAppActiveWindowChanged:
809 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
814 case kEventClassAppleEvent:
817 case kEventAppleEvent :
820 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
825 case kEventClassWindow:
828 case kEventWindowUpdate :
831 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
836 case kEventClassControl:
840 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
841 eventClass >> 24, (eventClass >> 16) & 0xFF,
842 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
847 SendEventToEventTarget (theEvent, theTarget);
848 ReleaseEvent(theEvent);
856 in_mouse_x = mouse_x;
857 in_mouse_y = mouse_y;