]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_agl.c
d88188713ad26a2a5ddcd97f0f7e48a3f60267ac
[xonotic/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 <Carbon/Carbon.h>
28 #include "quakedef.h"
29
30
31 // Tell startup code that we have a client
32 int cl_available = true;
33
34 qboolean vid_supportrefreshrate = true;
35
36 // AGL prototypes
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);
48
49 static qboolean mouse_avail = true;
50 static qboolean vid_usingmouse = false;
51 static float mouse_x, mouse_y;
52
53 static qboolean vid_isfullscreen = false;
54 static qboolean vid_usingvsync = false;
55
56 static int scr_width, scr_height;
57
58 static AGLContext context;
59 static WindowRef window;
60
61
62 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
63 {
64         *x = *y = 0;
65         *width = scr_width;
66         *height = scr_height;
67 }
68
69 static void IN_Activate( qboolean grab )
70 {
71         if (grab)
72         {
73                 if (!vid_usingmouse && mouse_avail && window)
74                 {
75                         Rect winBounds;
76                         CGPoint winCenter;
77
78                         SelectWindow(window);
79                         CGDisplayHideCursor(CGMainDisplayID());
80
81                         // Put the mouse cursor at the center of the window
82                         GetWindowBounds (window, kWindowContentRgn, &winBounds);
83                         winCenter.x = (winBounds.left + winBounds.right) / 2;
84                         winCenter.y = (winBounds.top + winBounds.bottom) / 2;
85                         CGWarpMouseCursorPosition(winCenter);
86
87                         // Lock the mouse pointer at its current position
88                         CGAssociateMouseAndMouseCursorPosition(false);
89
90                         mouse_x = mouse_y = 0;
91                         vid_usingmouse = true;
92                 }
93         }
94         else
95         {
96                 if (vid_usingmouse)
97                 {
98                         CGAssociateMouseAndMouseCursorPosition(true);
99                         CGDisplayShowCursor(CGMainDisplayID());
100
101                         vid_usingmouse = false;
102                 }
103         }
104 }
105
106 #define GAMMA_TABLE_SIZE 256
107 void VID_Finish (qboolean allowmousegrab)
108 {
109         qboolean vid_usemouse;
110         qboolean vid_usevsync;
111
112         // handle the mouse state when windowed if that's changed
113         vid_usemouse = false;
114         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
115                 vid_usemouse = true;
116         if (!vid_activewindow)
117                 vid_usemouse = false;
118         if (vid_isfullscreen)
119                 vid_usemouse = true;
120         IN_Activate(vid_usemouse);
121
122         // handle changes of the vsync option
123         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
124         if (vid_usingvsync != vid_usevsync)
125         {
126                 GLint sync = (vid_usevsync ? 1 : 0);
127
128                 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
129                 {
130                         vid_usingvsync = vid_usevsync;
131                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
132                 }
133                 else
134                         Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
135         }
136
137         if (r_render.integer)
138         {
139                 if (r_speeds.integer || gl_finish.integer)
140                         qglFinish();
141                 qaglSwapBuffers(context);
142         }
143         VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
144 }
145
146 int VID_SetGamma(unsigned short *ramps, int rampsize)
147 {
148         CGGammaValue table_red [GAMMA_TABLE_SIZE];
149         CGGammaValue table_green [GAMMA_TABLE_SIZE];
150         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
151         int i;
152
153         // Convert the unsigned short table into 3 float tables
154         for (i = 0; i < rampsize; i++)
155                 table_red[i] = (float)ramps[i] / 65535.0f;
156         for (i = 0; i < rampsize; i++)
157                 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
158         for (i = 0; i < rampsize; i++)
159                 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
160
161         if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
162         {
163                 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
164                 return false;
165         }
166
167         return true;
168 }
169
170 int VID_GetGamma(unsigned short *ramps, int rampsize)
171 {
172         CGGammaValue table_red [GAMMA_TABLE_SIZE];
173         CGGammaValue table_green [GAMMA_TABLE_SIZE];
174         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
175         CGTableCount actualsize = 0;
176         int i;
177
178         // Get the gamma ramps from the system
179         if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
180         {
181                 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
182                 return false;
183         }
184         if (actualsize != (unsigned int)rampsize)
185         {
186                 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
187                 return false;
188         }
189
190         // Convert the 3 float tables into 1 unsigned short table
191         for (i = 0; i < rampsize; i++)
192                 ramps[i] = table_red[i] * 65535.0f;
193         for (i = 0; i < rampsize; i++)
194                 ramps[i + rampsize] = table_green[i] * 65535.0f;
195         for (i = 0; i < rampsize; i++)
196                 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
197
198         return true;
199 }
200
201 void signal_handler(int sig)
202 {
203         printf("Received signal %d, exiting...\n", sig);
204         VID_RestoreSystemGamma();
205         Sys_Quit();
206         exit(0);
207 }
208
209 void InitSig(void)
210 {
211         signal(SIGHUP, signal_handler);
212         signal(SIGINT, signal_handler);
213         signal(SIGQUIT, signal_handler);
214         signal(SIGILL, signal_handler);
215         signal(SIGTRAP, signal_handler);
216         signal(SIGIOT, signal_handler);
217         signal(SIGBUS, signal_handler);
218         signal(SIGFPE, signal_handler);
219         signal(SIGSEGV, signal_handler);
220         signal(SIGTERM, signal_handler);
221 }
222
223 void VID_Init(void)
224 {
225         InitSig(); // trap evil signals
226 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
227         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
228                 mouse_avail = false;
229 }
230
231 static void *prjobj = NULL;
232
233 static void GL_CloseLibrary(void)
234 {
235         if (prjobj)
236                 dlclose(prjobj);
237         prjobj = NULL;
238         gl_driver[0] = 0;
239         gl_extensions = "";
240         gl_platform = "";
241         gl_platformextensions = "";
242 }
243
244 static int GL_OpenLibrary(void)
245 {
246         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
247
248         Con_Printf("Loading OpenGL driver %s\n", name);
249         GL_CloseLibrary();
250         if (!(prjobj = dlopen(name, RTLD_LAZY)))
251         {
252                 Con_Printf("Unable to open symbol list for %s\n", name);
253                 return false;
254         }
255         strcpy(gl_driver, name);
256         return true;
257 }
258
259 void *GL_GetProcAddress(const char *name)
260 {
261         return dlsym(prjobj, name);
262 }
263
264 void VID_Shutdown(void)
265 {
266         if (context == NULL && window == NULL)
267                 return;
268
269         IN_Activate(false);
270         VID_RestoreSystemGamma();
271
272         if (context != NULL)
273         {
274                 qaglDestroyContext(context);
275                 context = NULL;
276         }
277
278         if (vid_isfullscreen)
279                 CGReleaseAllDisplays();
280
281         if (window != NULL)
282         {
283                 DisposeWindow(window);
284                 window = NULL;
285         }
286
287         vid_hidden = true;
288         vid_isfullscreen = false;
289
290         GL_CloseLibrary();
291         Key_ClearStates ();
292 }
293
294 // Since the event handler can be called at any time, we store the events for later processing
295 static qboolean AsyncEvent_Quitting = false;
296 static qboolean AsyncEvent_Collapsed = false;
297 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
298 {
299         OSStatus err = noErr;
300
301         switch (GetEventKind (event))
302         {
303                 case kEventWindowClosed:
304                         AsyncEvent_Quitting = true;
305                         break;
306
307                 // Docked (start)
308                 case kEventWindowCollapsing:
309                         AsyncEvent_Collapsed = true;
310                         break;
311
312                 // Undocked / restored (end)
313                 case kEventWindowExpanded:
314                         AsyncEvent_Collapsed = false;
315                         break;
316
317                 default:
318                         err = eventNotHandledErr;
319                         break;
320         }
321
322         return err;
323 }
324
325 static void VID_ProcessPendingAsyncEvents (void)
326 {
327         // Collapsed / expanded
328         if (AsyncEvent_Collapsed != vid_hidden)
329         {
330                 vid_hidden = !vid_hidden;
331                 vid_activewindow = false;
332                 VID_RestoreSystemGamma();
333         }
334
335         // Closed
336         if (AsyncEvent_Quitting)
337         {
338                 Sys_Quit();
339         }
340 }
341
342 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen)
343 {
344         *attrib++ = AGL_RGBA;
345         *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
346         *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
347         *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
348         *attrib++ = AGL_DOUBLEBUFFER;
349         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
350
351         // if stencil is enabled, ask for alpha too
352         if (stencil)
353         {
354                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
355                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
356         }
357         if (fullscreen)
358                 *attrib++ = AGL_FULLSCREEN;
359         *attrib++ = AGL_NONE;
360 }
361
362 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
363 {
364     const EventTypeSpec winEvents[] =
365         {
366                 { kEventClassWindow, kEventWindowClosed },
367                 { kEventClassWindow, kEventWindowCollapsing },
368                 { kEventClassWindow, kEventWindowExpanded },
369         };
370         OSStatus carbonError;
371         Rect windowBounds;
372         CFStringRef windowTitle;
373         AGLPixelFormat pixelFormat;
374         GLint attributes [32];
375         GLenum error;
376
377         if (!GL_OpenLibrary())
378         {
379                 Con_Printf("Unable to load GL driver\n");
380                 return false;
381         }
382
383         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
384          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
385          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
386          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
387          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
388          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
389          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
390          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
391          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
392          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
393          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
394         )
395         {
396                 Con_Printf("AGL functions not found\n");
397                 ReleaseWindow(window);
398                 return false;
399         }
400
401         // Ignore the events from the previous window
402         AsyncEvent_Quitting = false;
403         AsyncEvent_Collapsed = false;
404
405         // Create the window, a bit towards the center of the screen
406         windowBounds.left = 100;
407         windowBounds.top = 100;
408         windowBounds.right = width + 100;
409         windowBounds.bottom = height + 100;
410         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
411         if (carbonError != noErr || window == NULL)
412         {
413                 Con_Printf("Unable to create window (error %d)\n", carbonError);
414                 return false;
415         }
416
417         // Set the window title
418         windowTitle = CFSTR("DarkPlaces AGL");
419         SetWindowTitleWithCFString(window, windowTitle);
420
421         // Install the callback function for the window events we can't get
422         // through ReceiveNextEvent (i.e. close, collapse, and expand)
423         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
424                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
425
426         // Create the desired attribute list
427         VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
428
429         if (!fullscreen)
430         {
431                 // Output to Window
432                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
433                 error = qaglGetError();
434                 if (error != AGL_NO_ERROR)
435                 {
436                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
437                                         (char *)qaglErrorString(error));
438                         ReleaseWindow(window);
439                         return false;
440                 }
441         }
442         else  // Output is fullScreen
443         {
444                 CGDirectDisplayID mainDisplay;
445                 CFDictionaryRef refDisplayMode;
446                 GDHandle gdhDisplay;
447
448                 // Get the mainDisplay and set resolution to current
449                 mainDisplay = CGMainDisplayID();
450                 CGDisplayCapture(mainDisplay);
451
452                 // TOCHECK: not sure whether or not it's necessary to change the resolution
453                 // "by hand", or if aglSetFullscreen does the job anyway
454                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
455                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
456                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
457
458                 // Set pixel format with built attribs
459                 // Note: specifying a device is *required* for AGL_FullScreen
460                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
461                 error = qaglGetError();
462                 if (error != AGL_NO_ERROR)
463                 {
464                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
465                                                 (char *)qaglErrorString(error));
466                         ReleaseWindow(window);
467                         return false;
468                 }
469         }
470
471         // Create a context using the pform
472         context = qaglCreateContext(pixelFormat, NULL);
473         error = qaglGetError();
474         if (error != AGL_NO_ERROR)
475         {
476                 Con_Printf("qaglCreateContext FAILED: %s\n",
477                                         (char *)qaglErrorString(error));
478         }
479
480         // Make the context the current one ('enable' it)
481         qaglSetCurrentContext(context);
482         error = qaglGetError();
483         if (error != AGL_NO_ERROR)
484         {
485                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
486                                         (char *)qaglErrorString(error));
487                 ReleaseWindow(window);
488                 return false;
489         }
490
491         // Discard pform
492         qaglDestroyPixelFormat(pixelFormat);
493
494         // Attempt fullscreen if requested
495         if (fullscreen)
496         {
497                 qaglSetFullScreen (context, width, height, refreshrate, 0);
498                 error = qaglGetError();
499                 if (error != AGL_NO_ERROR)
500                 {
501                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
502                                                 (char *)qaglErrorString(error));
503                         return false;
504                 }
505         }
506         else
507         {
508                 // Set Window as Drawable
509                 qaglSetDrawable(context, GetWindowPort(window));
510                 error = qaglGetError();
511                 if (error != AGL_NO_ERROR)
512                 {
513                         Con_Printf("qaglSetDrawable FAILED: %s\n",
514                                                 (char *)qaglErrorString(error));
515                         ReleaseWindow(window);
516                         return false;
517                 }
518         }
519
520         scr_width = width;
521         scr_height = height;
522
523         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
524                 Sys_Error("glGetString not found in %s", gl_driver);
525
526         gl_renderer = (const char *)qglGetString(GL_RENDERER);
527         gl_vendor = (const char *)qglGetString(GL_VENDOR);
528         gl_version = (const char *)qglGetString(GL_VERSION);
529         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
530         gl_platform = "AGL";
531         gl_videosyncavailable = true;
532
533         vid_isfullscreen = fullscreen;
534         vid_usingmouse = false;
535         vid_hidden = false;
536         vid_activewindow = true;
537         GL_Init();
538
539         SelectWindow(window);
540         ShowWindow(window);
541
542         return true;
543 }
544
545 static void Handle_KeyMod(UInt32 keymod)
546 {
547         const struct keymod_to_event_s { int keybit; keynum_t event; } keymod_events [] =
548         {
549                 {cmdKey,                                                K_AUX1},
550                 {shiftKey,                                              K_SHIFT},
551                 {alphaLock,                                             K_CAPSLOCK},
552                 {optionKey,                                             K_ALT},
553                 {controlKey,                                    K_CTRL},
554                 {kEventKeyModifierNumLockMask,  K_NUMLOCK},
555                 {kEventKeyModifierFnMask,               K_AUX2}
556         };
557         static UInt32 prev_keymod = 0;
558         unsigned int i;
559         UInt32 modChanges;
560
561         modChanges = prev_keymod ^ keymod;
562
563         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
564         {
565                 int keybit = keymod_events[i].keybit;
566
567                 if ((modChanges & keybit) != 0)
568                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
569         }
570
571         prev_keymod = keymod;
572 }
573
574 static void Handle_Key(unsigned char charcode, qboolean keypressed)
575 {
576         unsigned int keycode = 0;
577         char ascii = '\0';
578
579         switch (charcode)
580         {
581                 case kHomeCharCode:
582                         keycode = K_HOME;
583                         break;
584                 case kEnterCharCode:
585                         keycode = K_KP_ENTER;
586                         break;
587                 case kEndCharCode:
588                         keycode = K_END;
589                         break;
590                 case kBackspaceCharCode:
591                         keycode = K_BACKSPACE;
592                         break;
593                 case kTabCharCode:
594                         keycode = K_TAB;
595                         break;
596                 case kPageUpCharCode:
597                         keycode = K_PGUP;
598                         break;
599                 case kPageDownCharCode:
600                         keycode = K_PGDN;
601                         break;
602                 case kReturnCharCode:
603                         keycode = K_ENTER;
604                         break;
605                 case kEscapeCharCode:
606                         keycode = K_ESCAPE;
607                         break;
608                 case kLeftArrowCharCode:
609                         keycode = K_LEFTARROW;
610                         break;
611                 case kRightArrowCharCode:
612                         keycode = K_RIGHTARROW;
613                         break;
614                 case kUpArrowCharCode:
615                         keycode = K_UPARROW;
616                         break;
617                 case kDownArrowCharCode :
618                         keycode = K_DOWNARROW;
619                         break;
620                 case kDeleteCharCode:
621                         keycode = K_DEL;
622                         break;
623                 case 0:
624                 case 191:
625                         // characters 0 and 191 are sent by the mouse buttons (?!)
626                         break;
627                 default:
628                         if ('A' <= charcode && charcode <= 'Z')
629                         {
630                                 keycode = charcode + ('a' - 'A');  // lowercase it
631                                 ascii = charcode;
632                         }
633                         else if (charcode >= 32)
634                         {
635                                 keycode = charcode;
636                                 ascii = charcode;
637                         }
638                         else
639                                 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
640         }
641
642         if (keycode != 0)
643                 Key_Event(keycode, ascii, keypressed);
644 }
645
646 void Sys_SendKeyEvents(void)
647 {
648         EventRef theEvent;
649         EventTargetRef theTarget;
650
651         // Start by processing the asynchronous events we received since the previous frame
652         VID_ProcessPendingAsyncEvents();
653
654         theTarget = GetEventDispatcherTarget();
655         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
656         {
657                 UInt32 eventClass = GetEventClass(theEvent);
658                 UInt32 eventKind = GetEventKind(theEvent);
659
660                 switch (eventClass)
661                 {
662                         case kEventClassMouse:
663                         {
664                                 EventMouseButton theButton;
665                                 int key;
666
667                                 switch (eventKind)
668                                 {
669                                         case kEventMouseDown:
670                                         case kEventMouseUp:
671                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
672                                                 switch (theButton)
673                                                 {
674                                                         default:
675                                                         case kEventMouseButtonPrimary:
676                                                                 key = K_MOUSE1;
677                                                                 break;
678                                                         case kEventMouseButtonSecondary:
679                                                                 key = K_MOUSE2;
680                                                                 break;
681                                                         case kEventMouseButtonTertiary:
682                                                                 key = K_MOUSE3;
683                                                                 break;
684                                                 }
685                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
686                                                 break;
687
688                                         // Note: These two events are mutual exclusives
689                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
690                                         case kEventMouseMoved:
691                                         case kEventMouseDragged:
692                                         {
693                                                 HIPoint deltaPos;
694
695                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
696
697                                                 mouse_x += deltaPos.x;
698                                                 mouse_y += deltaPos.y;
699                                                 break;
700                                         }
701
702                                         case kEventMouseWheelMoved:
703                                         {
704                                                 SInt32 delta;
705                                                 unsigned int wheelEvent;
706
707                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
708
709                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
710                                                 Key_Event(wheelEvent, 0, true);
711                                                 Key_Event(wheelEvent, 0, false);
712                                                 break;
713                                         }
714
715                                         default:
716                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
717                                                 break;
718                                 }
719                         }
720
721                         case kEventClassKeyboard:
722                         {
723                                 char keycode;
724
725                                 switch (eventKind)
726                                 {
727                                         case kEventRawKeyDown:
728                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
729                                                 Handle_Key(keycode, true);
730                                                 break;
731
732                                         case kEventRawKeyRepeat:
733                                                 break;
734
735                                         case kEventRawKeyUp:
736                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
737                                                 Handle_Key(keycode, false);
738                                                 break;
739
740                                         case kEventRawKeyModifiersChanged:
741                                         {
742                                                 UInt32 keymod = 0;
743                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
744                                                 Handle_KeyMod(keymod);
745                                                 break;
746                                         }
747
748                                         case kEventHotKeyPressed:
749                                                 break;
750
751                                         case kEventHotKeyReleased:
752                                                 break;
753
754                                         case kEventMouseWheelMoved:
755                                                 break;
756
757                                         default:
758                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
759                                                 break;
760                                 }
761                                 break;
762                         }
763
764                         case kEventClassTextInput:
765                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
766                                 break;
767
768                         case kEventClassApplication:
769                                 switch (eventKind)
770                                 {
771                                         case kEventAppActivated :
772                                                 vid_activewindow = true;
773                                                 break;
774                                         case kEventAppDeactivated:
775                                                 vid_activewindow = false;
776                                                 VID_RestoreSystemGamma();
777                                                 break;
778                                         case kEventAppQuit:
779                                                 Sys_Quit();
780                                                 break;
781                                         case kEventAppActiveWindowChanged:
782                                                 break;
783                                         default:
784                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
785                                                 break;
786                                 }
787                                 break;
788
789                         case kEventClassAppleEvent:
790                                 switch (eventKind)
791                                 {
792                                         case kEventAppleEvent :
793                                                 break;
794                                         default:
795                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
796                                                 break;
797                                 }
798                                 break;
799
800                         case kEventClassWindow:
801                                 switch (eventKind)
802                                 {
803                                         case kEventWindowUpdate :
804                                                 break;
805                                         default:
806                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
807                                                 break;
808                                 }
809                                 break;
810
811                         case kEventClassControl:
812                                 break;
813
814                         default:
815                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
816                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
817                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
818                                                         eventKind);*/
819                                 break;
820                 }
821
822                 SendEventToEventTarget (theEvent, theTarget);
823                 ReleaseEvent(theEvent);
824         }
825 }
826
827 void IN_Move (void)
828 {
829         if (mouse_avail)
830         {
831                 in_mouse_x = mouse_x;
832                 in_mouse_y = mouse_y;
833         }
834         mouse_x = 0;
835         mouse_y = 0;
836 }