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