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