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 = false;
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 void (*qaglSwapBuffers) (AGLContext ctx);
46 static qboolean mouse_avail = true;
47 static qboolean vid_usingmouse = false;
48 static float mouse_x, mouse_y;
50 static qboolean vid_isfullscreen = false;
52 static int scr_width, scr_height;
54 static AGLContext context;
55 static WindowRef window;
58 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
65 static void IN_Activate( qboolean grab )
69 if (!vid_usingmouse && mouse_avail && window)
77 // Put the mouse cursor at the center of the window
78 GetWindowBounds (window, kWindowContentRgn, &winBounds);
79 winCenter.x = (winBounds.left + winBounds.right) / 2;
80 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
81 CGWarpMouseCursorPosition(winCenter);
83 // Lock the mouse pointer at its current position
84 CGAssociateMouseAndMouseCursorPosition(false);
86 mouse_x = mouse_y = 0;
87 vid_usingmouse = true;
94 CGAssociateMouseAndMouseCursorPosition(true);
97 vid_usingmouse = false;
102 void VID_Finish (void)
104 qboolean vid_usemouse;
106 // handle the mouse state when windowed if that's changed
107 vid_usemouse = false;
108 if (vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
110 if (!vid_activewindow)
111 vid_usemouse = false;
112 if (vid_isfullscreen)
114 IN_Activate(vid_usemouse);
116 if (r_render.integer)
118 if (r_speeds.integer || gl_finish.integer)
120 qaglSwapBuffers(context);
124 int VID_SetGamma(unsigned short *ramps)
130 int VID_GetGamma(unsigned short *ramps)
136 void signal_handler(int sig)
138 printf("Received signal %d, exiting...\n", sig);
139 VID_RestoreSystemGamma();
146 signal(SIGHUP, signal_handler);
147 signal(SIGINT, signal_handler);
148 signal(SIGQUIT, signal_handler);
149 signal(SIGILL, signal_handler);
150 signal(SIGTRAP, signal_handler);
151 signal(SIGIOT, signal_handler);
152 signal(SIGBUS, signal_handler);
153 signal(SIGFPE, signal_handler);
154 signal(SIGSEGV, signal_handler);
155 signal(SIGTERM, signal_handler);
160 InitSig(); // trap evil signals
161 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
162 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
166 static void *prjobj = NULL;
168 static void GL_CloseLibrary(void)
176 gl_platformextensions = "";
179 static int GL_OpenLibrary(void)
181 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
183 Con_Printf("Loading OpenGL driver %s\n", name);
185 if (!(prjobj = dlopen(name, RTLD_LAZY)))
187 Con_Printf("Unable to open symbol list for %s\n", name);
190 strcpy(gl_driver, name);
194 void *GL_GetProcAddress(const char *name)
196 return dlsym(prjobj, name);
199 void VID_Shutdown(void)
201 if (context == NULL || window == NULL)
205 VID_RestoreSystemGamma();
209 qaglDestroyContext(context);
215 DisposeWindow(window);
220 vid_isfullscreen = false;
226 // Since the event handler can be called at any time, we store the events for later processing
227 static qboolean AsyncEvent_Quitting = false;
228 static qboolean AsyncEvent_Collapsed = false;
229 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
231 OSStatus err = noErr;
233 switch (GetEventKind (event))
235 case kEventWindowClosed:
236 //Con_Printf(">> kEventWindowClosed (received) <<\n");
237 AsyncEvent_Quitting = true;
241 case kEventWindowCollapsing:
242 //Con_Printf(">> kEventWindowCollapsing (received) <<\n");
243 AsyncEvent_Collapsed = true;
246 // Undocked / restored (end)
247 case kEventWindowExpanded:
248 //Con_Printf(">> kEventWindowExpanded (received) <<\n");
249 AsyncEvent_Collapsed = false;
253 err = eventNotHandledErr;
260 static void VID_ProcessPendingAsyncEvents (void)
262 // Collapsed / expanded
263 if (AsyncEvent_Collapsed != vid_hidden)
267 Con_Printf(">> kEventWindowExpanded (processed) <<\n");
269 Con_Printf(">> kEventWindowCollapsing (processed) <<\n");
272 vid_hidden = !vid_hidden;
273 vid_activewindow = false;
274 VID_RestoreSystemGamma();
278 if (AsyncEvent_Quitting)
280 //Con_Printf(">> kEventWindowClosed (processed) <<\n");
285 static void VID_BuildAGLAttrib(GLint *attrib, int stencil, qboolean fullscreen)
287 *attrib++ = AGL_RGBA;
288 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
289 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
290 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
291 *attrib++ = AGL_DOUBLEBUFFER;
292 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
293 // if stencil is enabled, ask for alpha too
296 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
297 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
300 *attrib++ = AGL_FULLSCREEN;
301 *attrib++ = AGL_NONE;
304 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
306 const EventTypeSpec winEvents[] =
308 { kEventClassWindow, kEventWindowClosed },
309 { kEventClassWindow, kEventWindowCollapsing },
310 { kEventClassWindow, kEventWindowExpanded },
312 OSStatus carbonError;
315 AGLPixelFormat pixelFormat;
316 GLint attributes [32];
318 if (!GL_OpenLibrary())
320 Con_Printf("Unable to load GL driver\n");
324 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
325 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
326 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
327 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
328 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
329 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
330 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
331 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
334 Con_Printf("AGL functions not found\n");
335 ReleaseWindow(window);
339 // Ignore the events from the previous window
340 AsyncEvent_Quitting = false;
341 AsyncEvent_Collapsed = false;
344 SetRect(&windowBounds, 0, 0, width, height);
345 OffsetRect(&windowBounds, 100, 100); // move it a bit towards the center of the screen
346 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
347 if (carbonError != noErr || window == NULL)
349 Con_Printf("Unable to create window (error %d)\n", carbonError);
353 // Set the window title
354 CFStringRef windowTitle = CFSTR("DarkPlaces AGL");
355 SetWindowTitleWithCFString(window, windowTitle);
356 CFRelease(windowTitle);
358 // Install the callback function for the window events we can't get
359 // through ReceiveNextEvent (i.e. close, collapse, and expand)
360 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
361 GetEventTypeCount(winEvents), winEvents, window, NULL);
363 screen = GetGWorldDevice(GetWindowPort(window));
366 Con_Printf("Unable to get GDevice for window\n");
367 ReleaseWindow(window);
371 // Create and set pixel format
372 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
373 pixelFormat = qaglChoosePixelFormat(&screen, 1, attributes);
374 if (pixelFormat == NULL)
376 Con_Printf("Unable to create pixel format\n");
377 ReleaseWindow(window);
381 // Set context and show the window
382 context = qaglCreateContext(pixelFormat, NULL);
384 Sys_Error ("aglCreateContext failed");
387 if (!qaglSetFullScreen (context, width, height, 0, 0))
388 Sys_Error("aglSetFullScreen failed");
389 vid_isfullscreen = true;
393 if (!qaglSetDrawable(context, GetWindowPort(window)))
394 Sys_Error ("aglSetDrawable failed");
396 if (!qaglSetCurrentContext(context))
397 Sys_Error ("aglSetCurrentContext failed");
398 qaglDestroyPixelFormat(pixelFormat);
403 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
404 Sys_Error("glGetString not found in %s", gl_driver);
406 gl_renderer = (const char *)qglGetString(GL_RENDERER);
407 gl_vendor = (const char *)qglGetString(GL_VENDOR);
408 gl_version = (const char *)qglGetString(GL_VERSION);
409 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
411 gl_videosyncavailable = false;
413 vid_usingmouse = false;
415 vid_activewindow = true;
418 SelectWindow(window);
424 static void Handle_KeyMod(UInt32 keymod)
426 static UInt32 prev_keymod = 0;
427 UInt32 modChanges = prev_keymod ^ keymod;
429 if ((modChanges & cmdKey) != 0)
431 Key_Event(K_AUX1, '\0', (keymod & cmdKey) != 0);
433 if ((modChanges & shiftKey) != 0 || (modChanges & rightShiftKey) != 0)
435 Key_Event(K_SHIFT, '\0', (keymod & shiftKey) != 0);
437 if ((modChanges & alphaLock) != 0)
439 Key_Event(K_CAPSLOCK, '\0', (keymod & alphaLock) != 0);
441 if ((modChanges & optionKey) != 0 || (modChanges & rightOptionKey) != 0)
443 Key_Event(K_ALT, '\0', (keymod & optionKey) != 0);
445 if ((modChanges & controlKey) != 0 || (modChanges & rightControlKey) != 0)
447 Key_Event(K_CTRL, '\0', (keymod & controlKey) != 0);
449 if ((modChanges & kEventKeyModifierNumLockMask) != 0)
451 Key_Event(K_NUMLOCK, '\0', (keymod & kEventKeyModifierNumLockMask) != 0);
453 if ((modChanges & kEventKeyModifierFnMask) != 0)
455 Key_Event(K_AUX2, '\0', (keymod & kEventKeyModifierFnMask) != 0);
458 prev_keymod = keymod;
461 static void Handle_Key(unsigned char charcode, qboolean keypressed)
463 unsigned int keycode = 0;
472 keycode = K_KP_ENTER;
477 case kBackspaceCharCode:
478 keycode = K_BACKSPACE;
483 case kPageUpCharCode:
486 case kPageDownCharCode:
489 case kReturnCharCode:
492 case kEscapeCharCode:
495 case kLeftArrowCharCode:
496 keycode = K_LEFTARROW;
498 case kRightArrowCharCode:
499 keycode = K_RIGHTARROW;
501 case kUpArrowCharCode:
504 case kDownArrowCharCode :
505 keycode = K_DOWNARROW;
507 case kDeleteCharCode:
511 // char 191 is sent by the mouse buttons (?!)
514 if ('A' <= charcode && charcode <= 'Z')
516 keycode = charcode + ('a' - 'A'); // lowercase it
519 else if (32 <= charcode)
525 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
529 Key_Event(keycode, ascii, keypressed);
532 void Sys_SendKeyEvents(void)
535 EventTargetRef theTarget;
537 // Start by processing the asynchronous events we received since the previous frame
538 VID_ProcessPendingAsyncEvents();
540 theTarget = GetEventDispatcherTarget();
541 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
543 UInt32 eventClass = GetEventClass(theEvent);
544 UInt32 eventKind = GetEventKind(theEvent);
548 case kEventClassMouse:
550 EventMouseButton theButton;
555 case kEventMouseDown:
557 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
561 case kEventMouseButtonPrimary:
563 //Con_Printf(">> kEventMouseButtonPrimary <<\n");
565 case kEventMouseButtonSecondary:
567 //Con_Printf(">> kEventMouseButtonSecondary <<\n");
569 case kEventMouseButtonTertiary:
571 //Con_Printf(">> kEventMouseButtonTertiary <<\n");
574 Key_Event(key, '\0', eventKind == kEventMouseDown);
577 case kEventMouseMoved:
581 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
582 //Con_Printf(">> kEventMouseMoved (%f, %f) <<\n", deltaPos.x, deltaPos.y);
584 mouse_x += deltaPos.x;
585 mouse_y += deltaPos.y;
589 case kEventMouseWheelMoved:
592 unsigned int wheelEvent;
594 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
595 //Con_Printf(">> kEventMouseWheelMoved (delta: %d) <<\n", delta);
597 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
598 Key_Event(wheelEvent, 0, true);
599 Key_Event(wheelEvent, 0, false);
603 case kEventMouseDragged:
604 //Con_Printf(">> kEventMouseDragged <<\n");
608 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
613 case kEventClassKeyboard:
619 case kEventRawKeyDown:
620 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
621 Handle_Key(keycode, true);
622 //Con_Printf(">> kEventRawKeyDown (%d) <<\n", keycode);
625 case kEventRawKeyRepeat:
626 //Con_Printf(">> kEventRawKeyRepeat <<\n");
630 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
631 Handle_Key(keycode, false);
632 //Con_Printf(">> kEventRawKeyUp (%d) <<\n", keycode);
635 case kEventRawKeyModifiersChanged:
638 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
639 Handle_KeyMod(keymod);
640 //Con_Printf(">> kEventRawKeyModifiersChanged (0x%08X) <<\n", keymod);
644 case kEventHotKeyPressed:
645 //Con_Printf(">> kEventHotKeyPressed <<\n");
648 case kEventHotKeyReleased:
649 //Con_Printf(">> kEventHotKeyReleased <<\n");
652 case kEventMouseWheelMoved:
653 //Con_Printf(">> kEventMouseWheelMoved - via a keyboard event (!?) <<\n");
657 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
663 case kEventClassTextInput:
664 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
667 case kEventClassApplication:
670 case kEventAppActivated :
671 //Con_Printf(">> kEventAppActivated <<\n");
672 vid_activewindow = true;
674 case kEventAppDeactivated:
675 //Con_Printf(">> kEventAppDeactivated <<\n");
676 vid_activewindow = false;
677 VID_RestoreSystemGamma();
680 //Con_Printf(">> kEventAppQuit <<\n");
683 case kEventAppActiveWindowChanged:
684 //Con_Printf(">> kEventAppActiveWindowChanged <<\n");
687 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
692 case kEventClassAppleEvent:
695 case kEventAppleEvent :
696 //Con_Printf(">> kEventAppleEvent <<\n");
699 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
704 case kEventClassWindow:
707 case kEventWindowUpdate :
708 //Con_Printf(">> kEventWindowUpdate <<\n");
711 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
716 case kEventClassControl:
717 //Con_Printf(">> kEventClassControl (%d) <<\n", eventKind);
721 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
722 eventClass >> 24, (eventClass >> 16) & 0xFF,
723 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
728 SendEventToEventTarget (theEvent, theTarget);
729 ReleaseEvent(theEvent);
737 in_mouse_x = mouse_x;
738 in_mouse_y = mouse_y;