4 Mac OS X OpenGL and input module, using Carbon and AGL
6 Copyright (C) 2005 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 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
42 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
43 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
44 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
45 void (*qaglSwapBuffers) (AGLContext ctx);
47 static qboolean mouse_avail = true;
48 static qboolean vid_usingmouse = false;
49 static float mouse_x, mouse_y;
51 static qboolean vid_isfullscreen = false;
52 static qboolean vid_usingvsync = false;
54 static int scr_width, scr_height;
56 static AGLContext context;
57 static WindowRef window;
60 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
67 static void IN_Activate( qboolean grab )
71 if (!vid_usingmouse && mouse_avail && window)
79 // Put the mouse cursor at the center of the window
80 GetWindowBounds (window, kWindowContentRgn, &winBounds);
81 winCenter.x = (winBounds.left + winBounds.right) / 2;
82 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
83 CGWarpMouseCursorPosition(winCenter);
85 // Lock the mouse pointer at its current position
86 CGAssociateMouseAndMouseCursorPosition(false);
88 mouse_x = mouse_y = 0;
89 vid_usingmouse = true;
96 CGAssociateMouseAndMouseCursorPosition(true);
99 vid_usingmouse = false;
104 void VID_Finish (qboolean allowmousegrab)
106 qboolean vid_usemouse;
107 qboolean vid_usevsync;
109 // handle the mouse state when windowed if that's changed
110 vid_usemouse = false;
111 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
113 if (!vid_activewindow)
114 vid_usemouse = false;
115 if (vid_isfullscreen)
117 IN_Activate(vid_usemouse);
119 // handle changes of the vsync option
120 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
121 if (vid_usingvsync != vid_usevsync)
123 GLint sync = (vid_usevsync ? 1 : 0);
125 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
127 vid_usingvsync = vid_usevsync;
128 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
131 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
134 if (r_render.integer)
136 if (r_speeds.integer || gl_finish.integer)
138 qaglSwapBuffers(context);
142 #define GAMMA_TABLE_SIZE 256
143 int VID_SetGamma(unsigned short *ramps)
145 CGGammaValue table_red [GAMMA_TABLE_SIZE];
146 CGGammaValue table_green [GAMMA_TABLE_SIZE];
147 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
150 // Convert the unsigned short table into 3 float tables
151 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
152 table_red[i] = (float)ramps[i] / 65535.0f;
153 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
154 table_green[i] = (float)ramps[i + GAMMA_TABLE_SIZE] / 65535.0f;
155 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
156 table_blue[i] = (float)ramps[i + 2 * GAMMA_TABLE_SIZE] / 65535.0f;
158 if (CGSetDisplayTransferByTable(CGMainDisplayID(), GAMMA_TABLE_SIZE, table_red, table_green, table_blue) != CGDisplayNoErr)
160 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
167 int VID_GetGamma(unsigned short *ramps)
169 CGGammaValue table_red [GAMMA_TABLE_SIZE];
170 CGGammaValue table_green [GAMMA_TABLE_SIZE];
171 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
172 CGTableCount actualsize = 0;
175 // Get the gamma ramps from the system
176 if (CGGetDisplayTransferByTable(CGMainDisplayID(), GAMMA_TABLE_SIZE, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
178 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
181 if (actualsize != GAMMA_TABLE_SIZE)
183 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, GAMMA_TABLE_SIZE);
187 // Convert the 3 float tables into 1 unsigned short table
188 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
189 ramps[i] = table_red[i] * 65535.0f;
190 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
191 ramps[i + GAMMA_TABLE_SIZE] = table_green[i] * 65535.0f;
192 for (i = 0; i < GAMMA_TABLE_SIZE; i++)
193 ramps[i + 2 * GAMMA_TABLE_SIZE] = table_blue[i] * 65535.0f;
198 void signal_handler(int sig)
200 printf("Received signal %d, exiting...\n", sig);
201 VID_RestoreSystemGamma();
208 signal(SIGHUP, signal_handler);
209 signal(SIGINT, signal_handler);
210 signal(SIGQUIT, signal_handler);
211 signal(SIGILL, signal_handler);
212 signal(SIGTRAP, signal_handler);
213 signal(SIGIOT, signal_handler);
214 signal(SIGBUS, signal_handler);
215 signal(SIGFPE, signal_handler);
216 signal(SIGSEGV, signal_handler);
217 signal(SIGTERM, signal_handler);
222 InitSig(); // trap evil signals
223 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
224 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
228 static void *prjobj = NULL;
230 static void GL_CloseLibrary(void)
238 gl_platformextensions = "";
241 static int GL_OpenLibrary(void)
243 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
245 Con_Printf("Loading OpenGL driver %s\n", name);
247 if (!(prjobj = dlopen(name, RTLD_LAZY)))
249 Con_Printf("Unable to open symbol list for %s\n", name);
252 strcpy(gl_driver, name);
256 void *GL_GetProcAddress(const char *name)
258 return dlsym(prjobj, name);
261 void VID_Shutdown(void)
263 if (context == NULL || window == NULL)
267 VID_RestoreSystemGamma();
271 qaglDestroyContext(context);
277 DisposeWindow(window);
282 vid_isfullscreen = false;
288 // Since the event handler can be called at any time, we store the events for later processing
289 static qboolean AsyncEvent_Quitting = false;
290 static qboolean AsyncEvent_Collapsed = false;
291 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
293 OSStatus err = noErr;
295 switch (GetEventKind (event))
297 case kEventWindowClosed:
298 AsyncEvent_Quitting = true;
302 case kEventWindowCollapsing:
303 AsyncEvent_Collapsed = true;
306 // Undocked / restored (end)
307 case kEventWindowExpanded:
308 AsyncEvent_Collapsed = false;
312 err = eventNotHandledErr;
319 static void VID_ProcessPendingAsyncEvents (void)
321 // Collapsed / expanded
322 if (AsyncEvent_Collapsed != vid_hidden)
324 vid_hidden = !vid_hidden;
325 vid_activewindow = false;
326 VID_RestoreSystemGamma();
330 if (AsyncEvent_Quitting)
336 static void VID_BuildAGLAttrib(GLint *attrib, int stencil, qboolean fullscreen)
338 *attrib++ = AGL_RGBA;
339 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
340 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
341 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
342 *attrib++ = AGL_DOUBLEBUFFER;
343 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
345 // if stencil is enabled, ask for alpha too
348 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
349 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
352 *attrib++ = AGL_FULLSCREEN;
353 *attrib++ = AGL_NONE;
356 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
358 const EventTypeSpec winEvents[] =
360 { kEventClassWindow, kEventWindowClosed },
361 { kEventClassWindow, kEventWindowCollapsing },
362 { kEventClassWindow, kEventWindowExpanded },
364 OSStatus carbonError;
367 AGLPixelFormat pixelFormat;
368 GLint attributes [32];
370 if (!GL_OpenLibrary())
372 Con_Printf("Unable to load GL driver\n");
376 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
377 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
378 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
379 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
380 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
381 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
382 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
383 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
384 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
387 Con_Printf("AGL functions not found\n");
388 ReleaseWindow(window);
392 // Ignore the events from the previous window
393 AsyncEvent_Quitting = false;
394 AsyncEvent_Collapsed = false;
397 SetRect(&windowBounds, 0, 0, width, height);
398 OffsetRect(&windowBounds, 100, 100); // move it a bit towards the center of the screen
399 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
400 if (carbonError != noErr || window == NULL)
402 Con_Printf("Unable to create window (error %d)\n", carbonError);
406 // Set the window title
407 CFStringRef windowTitle = CFSTR("DarkPlaces AGL");
408 SetWindowTitleWithCFString(window, windowTitle);
409 CFRelease(windowTitle);
411 // Install the callback function for the window events we can't get
412 // through ReceiveNextEvent (i.e. close, collapse, and expand)
413 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
414 GetEventTypeCount(winEvents), winEvents, window, NULL);
416 screen = GetGWorldDevice(GetWindowPort(window));
419 Con_Printf("Unable to get GDevice for window\n");
420 ReleaseWindow(window);
424 // Create and set pixel format
425 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
426 pixelFormat = qaglChoosePixelFormat(&screen, 1, attributes);
427 if (pixelFormat == NULL)
429 Con_Printf("Unable to create pixel format\n");
430 ReleaseWindow(window);
434 // Set context and show the window
435 context = qaglCreateContext(pixelFormat, NULL);
437 Sys_Error ("aglCreateContext failed");
440 if (!qaglSetFullScreen (context, width, height, refreshrate, 0))
441 Sys_Error("aglSetFullScreen failed");
442 vid_isfullscreen = true;
446 if (!qaglSetDrawable(context, GetWindowPort(window)))
447 Sys_Error ("aglSetDrawable failed");
449 if (!qaglSetCurrentContext(context))
450 Sys_Error ("aglSetCurrentContext failed");
451 qaglDestroyPixelFormat(pixelFormat);
456 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
457 Sys_Error("glGetString not found in %s", gl_driver);
459 gl_renderer = (const char *)qglGetString(GL_RENDERER);
460 gl_vendor = (const char *)qglGetString(GL_VENDOR);
461 gl_version = (const char *)qglGetString(GL_VERSION);
462 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
464 gl_videosyncavailable = true;
466 vid_usingmouse = false;
468 vid_activewindow = true;
471 SelectWindow(window);
477 static void Handle_KeyMod(UInt32 keymod)
479 static UInt32 prev_keymod = 0;
480 UInt32 modChanges = prev_keymod ^ keymod;
482 if ((modChanges & cmdKey) != 0)
484 Key_Event(K_AUX1, '\0', (keymod & cmdKey) != 0);
486 if ((modChanges & shiftKey) != 0 || (modChanges & rightShiftKey) != 0)
488 Key_Event(K_SHIFT, '\0', (keymod & shiftKey) != 0);
490 if ((modChanges & alphaLock) != 0)
492 Key_Event(K_CAPSLOCK, '\0', (keymod & alphaLock) != 0);
494 if ((modChanges & optionKey) != 0 || (modChanges & rightOptionKey) != 0)
496 Key_Event(K_ALT, '\0', (keymod & optionKey) != 0);
498 if ((modChanges & controlKey) != 0 || (modChanges & rightControlKey) != 0)
500 Key_Event(K_CTRL, '\0', (keymod & controlKey) != 0);
502 if ((modChanges & kEventKeyModifierNumLockMask) != 0)
504 Key_Event(K_NUMLOCK, '\0', (keymod & kEventKeyModifierNumLockMask) != 0);
506 if ((modChanges & kEventKeyModifierFnMask) != 0)
508 Key_Event(K_AUX2, '\0', (keymod & kEventKeyModifierFnMask) != 0);
511 prev_keymod = keymod;
514 static void Handle_Key(unsigned char charcode, qboolean keypressed)
516 unsigned int keycode = 0;
525 keycode = K_KP_ENTER;
530 case kBackspaceCharCode:
531 keycode = K_BACKSPACE;
536 case kPageUpCharCode:
539 case kPageDownCharCode:
542 case kReturnCharCode:
545 case kEscapeCharCode:
548 case kLeftArrowCharCode:
549 keycode = K_LEFTARROW;
551 case kRightArrowCharCode:
552 keycode = K_RIGHTARROW;
554 case kUpArrowCharCode:
557 case kDownArrowCharCode :
558 keycode = K_DOWNARROW;
560 case kDeleteCharCode:
565 // characters 0 and 191 are sent by the mouse buttons (?!)
568 if ('A' <= charcode && charcode <= 'Z')
570 keycode = charcode + ('a' - 'A'); // lowercase it
573 else if (charcode >= 32)
579 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
583 Key_Event(keycode, ascii, keypressed);
586 void Sys_SendKeyEvents(void)
589 EventTargetRef theTarget;
591 // Start by processing the asynchronous events we received since the previous frame
592 VID_ProcessPendingAsyncEvents();
594 theTarget = GetEventDispatcherTarget();
595 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
597 UInt32 eventClass = GetEventClass(theEvent);
598 UInt32 eventKind = GetEventKind(theEvent);
602 case kEventClassMouse:
604 EventMouseButton theButton;
609 case kEventMouseDown:
611 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
615 case kEventMouseButtonPrimary:
618 case kEventMouseButtonSecondary:
621 case kEventMouseButtonTertiary:
625 Key_Event(key, '\0', eventKind == kEventMouseDown);
628 case kEventMouseMoved:
632 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
634 mouse_x += deltaPos.x;
635 mouse_y += deltaPos.y;
639 case kEventMouseWheelMoved:
642 unsigned int wheelEvent;
644 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
646 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
647 Key_Event(wheelEvent, 0, true);
648 Key_Event(wheelEvent, 0, false);
652 case kEventMouseDragged:
656 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
661 case kEventClassKeyboard:
667 case kEventRawKeyDown:
668 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
669 Handle_Key(keycode, true);
672 case kEventRawKeyRepeat:
676 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
677 Handle_Key(keycode, false);
680 case kEventRawKeyModifiersChanged:
683 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
684 Handle_KeyMod(keymod);
688 case kEventHotKeyPressed:
691 case kEventHotKeyReleased:
694 case kEventMouseWheelMoved:
698 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
704 case kEventClassTextInput:
705 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
708 case kEventClassApplication:
711 case kEventAppActivated :
712 vid_activewindow = true;
714 case kEventAppDeactivated:
715 vid_activewindow = false;
716 VID_RestoreSystemGamma();
721 case kEventAppActiveWindowChanged:
724 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
729 case kEventClassAppleEvent:
732 case kEventAppleEvent :
735 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
740 case kEventClassWindow:
743 case kEventWindowUpdate :
746 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
751 case kEventClassControl:
755 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
756 eventClass >> 24, (eventClass >> 16) & 0xFF,
757 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
762 SendEventToEventTarget (theEvent, theTarget);
763 ReleaseEvent(theEvent);
771 in_mouse_x = mouse_x;
772 in_mouse_y = mouse_y;