]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Removed an unused function
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22
23 #ifdef WIN32
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
27 #include <windows.h>
28 #undef UINT8
29 #undef UINT16
30 #undef boolean
31 #endif
32
33
34
35 #include "Game.h"
36 extern "C" {
37         #include "zlib.h"
38         #include "png.h"
39    #ifdef WIN32
40                 #define INT32 INT32_jpeg
41                 #include "jpeglib.h"
42                 #undef INT32
43         #else
44                 #include "jpeglib.h"
45         #endif
46 }
47
48 static bool load_image(const char * fname, TGAImageRec & tex);
49 static bool load_png(const char * fname, TGAImageRec & tex);
50 static bool load_jpg(const char * fname, TGAImageRec & tex);
51 static bool save_image(const char * fname);
52 static bool save_png(const char * fname);
53
54
55 #include "openal_wrapper.h"
56
57 // ADDED GWC
58 #ifdef _MSC_VER
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
62 #endif
63
64 extern float multiplier;
65 extern float sps;
66 extern float realmultiplier;
67 extern int slomo;
68 extern bool cellophane;
69 // MODIFIED GWC
70 //extern int terraindetail;
71 //extern int texdetail;
72 extern float terraindetail;
73 extern float texdetail;
74
75 extern bool osx;
76 extern int numplayers;
77 extern bool freeze;
78 extern Person player[maxplayers];
79 extern bool stillloading;
80 extern int mainmenu;
81 /*extern*/ bool gameFocused;
82
83 extern float slomospeed;
84 extern float slomofreq;
85
86
87
88 #include <math.h>
89 #include <stdio.h>
90 #include <string.h>
91 #include <fstream>
92 #include <iostream>
93 #include "gamegl.h"
94 #include "MacCompatibility.h"
95 #include "Settings.h"
96
97 #ifdef WIN32
98 #include <shellapi.h>
99 #include "win-res/resource.h"
100 #endif
101
102 using namespace std;
103
104
105
106 SDL_Rect **resolutions = NULL;
107 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
108 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
109 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
110 static SDL_Rect *hardcoded_resolutions[] = {
111     &rect_1024_768,
112     &rect_800_600,
113     &rect_640_480,
114     NULL
115 };
116
117
118
119 unsigned int resolutionDepths[8][2] = {0};
120
121 int closestResolution(int width, int height);
122 int resolutionID(int width, int height);
123
124 void ReportError (char * strError);
125
126 void DrawGL(Game & game);
127
128 void CreateGLWindow (void);
129 Boolean SetUp (Game & game);
130 void DoUpdate (Game & game);
131
132 void DoEvent (void);
133 void CleanUp (void);
134
135
136 // statics/globals (internal only) ------------------------------------------
137 #ifndef WIN32
138 typedef struct tagPOINT { 
139   int x;
140   int y;
141 } POINT, *PPOINT; 
142 #endif
143
144
145
146 #ifdef _MSC_VER
147 #pragma warning(push)
148 #pragma warning(disable: 4273)
149 #endif
150
151 #define GL_FUNC(ret,fn,params,call,rt) \
152     extern "C" { \
153         static ret (GLAPIENTRY *p##fn) params = NULL; \
154         ret GLAPIENTRY fn params { rt p##fn call; } \
155     }
156 #include "glstubs.h"
157 #undef GL_FUNC
158
159 #ifdef _MSC_VER
160 #pragma warning(pop)
161 #endif
162
163 static bool lookup_glsym(const char *funcname, void **func)
164 {
165     *func = SDL_GL_GetProcAddress(funcname);
166     if (*func == NULL)
167     {
168         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
169         return false;
170     }
171     return true;
172 }
173
174 static bool lookup_all_glsyms(void)
175 {
176     bool retval = true;
177     #define GL_FUNC(ret,fn,params,call,rt) \
178         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
179     #include "glstubs.h"
180     #undef GL_FUNC
181     return retval;
182 }
183
184 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
185 {
186     // no-op.
187 }
188
189
190
191 void sdlGetCursorPos(POINT *pt)
192 {
193     SDL_GetMouseState(&(pt->x), &(pt->y));
194 }
195 #define GetCursorPos(x) sdlGetCursorPos(x)
196 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
197 #define ScreenToClient(x, pt)
198 #define ClientToScreen(x, pt)
199 #ifdef MessageBox
200 #undef MessageBox
201 #endif
202 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
203
204
205 Point delta;
206
207 static bool g_button, fullscreen = true;
208
209
210 // Menu defs
211 enum 
212 {
213         kFileQuit = 1
214 };
215
216 enum 
217 {
218         kForegroundSleep = 10,
219         kBackgroundSleep = 10000
220 };
221
222
223 int kContextWidth;
224 int kContextHeight;
225
226 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
227
228 GLuint gFontList;
229 char gcstrMode [256] = "";
230
231 UInt32 gSleepTime = kForegroundSleep;
232 Boolean gDone = false, gfFrontProcess = true;
233
234 Game * pgame = 0;
235
236 #ifndef __MINGW32__
237 static int _argc = 0;
238 static char **_argv = NULL;
239 #endif
240
241 bool cmdline(const char *cmd)
242 {
243     for (int i = 1; i < _argc; i++)
244     {
245         char *arg = _argv[i];
246         while (*arg == '-')
247             arg++;
248         if (strcasecmp(arg, cmd) == 0)
249             return true;
250     }
251
252     return false;
253 }
254
255
256 // --------------------------------------------------------------------------
257
258 void ReportError (char * strError)
259 {
260 #ifdef _MSC_VER  // !!! FIXME.  --ryan.
261         throw std::exception( strError);
262 #endif
263
264         /*      char errMsgCStr [256];
265         Str255 strErr;
266
267         sprintf (errMsgCStr, "%s", strError); 
268
269         // out as debug string
270         CToPStr (strErr, errMsgCStr);
271         DebugStr (strErr);
272         */
273 }
274
275 //-----------------------------------------------------------------------------------------------------------------------
276
277 // OpenGL Drawing
278
279 void DrawGL (Game & game)
280 {
281         if ( stereomode == stereoNone ) {
282                 game.DrawGLScene(stereoCenter);
283         } else {
284                 game.DrawGLScene(stereoLeft);
285                 game.DrawGLScene(stereoRight);
286         }
287 }
288
289 static void sdlEventProc(const SDL_Event &e, Game &game)
290 {
291     int val;
292     SDLMod mod;
293
294     switch(e.type)
295         {
296         case SDL_MOUSEMOTION:
297             game.deltah += e.motion.xrel;
298             game.deltav += e.motion.yrel;
299             return;
300
301         case SDL_KEYDOWN:
302             if ((e.key.keysym.sym == SDLK_g) &&
303                                 (e.key.keysym.mod & KMOD_CTRL) &&
304                                 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
305                                 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
306                         } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
307                                 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
308             }
309             return;
310     }
311 }
312
313
314 // --------------------------------------------------------------------------
315
316 static Point gMidPoint;
317
318 Boolean SetUp (Game & game)
319 {
320         char string[10];
321
322         LOGFUNC;
323
324         randSeed = UpTime().lo;
325
326         osx = 0;
327         cellophane=0;
328         texdetail=4;
329         terraindetail=2;
330         slomospeed=0.25;
331         slomofreq=8012;
332         numplayers=1;
333         
334         DefaultSettings(game);
335
336     if (!SDL_WasInit(SDL_INIT_VIDEO))
337         if (SDL_Init(SDL_INIT_VIDEO) == -1)
338         {
339             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
340             return false;
341         }
342         if(!LoadSettings(game)) {
343                 fprintf(stderr, "Failed to load config, creating default\n");
344                 SaveSettings(game);
345         }
346         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
347                 kBitsPerPixel=16;
348         }
349
350         if (SDL_GL_LoadLibrary(NULL) == -1)
351         {
352                 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
353                 SDL_Quit();
354                 return false;
355         }
356
357         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
358         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
359                 res = hardcoded_resolutions;
360
361         // reverse list (it was sorted biggest to smallest by SDL)...
362         int count;
363         for (count = 0; res[count]; count++)
364         {
365                 if ((res[count]->w < 640) || (res[count]->h < 480))
366                         break;   // sane lower limit.
367         }
368
369         static SDL_Rect *resolutions_block = NULL;
370         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
371         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
372         if ((resolutions_block == NULL) || (resolutions == NULL))
373         {
374                 SDL_Quit();
375                 fprintf(stderr, "Out of memory!\n");
376                 return false;
377         }
378
379         resolutions[count--] = NULL;
380         for (int i = 0; count >= 0; i++, count--)
381         {
382                 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
383                 resolutions[count] = &resolutions_block[count];
384         }
385
386         if (cmdline("showresolutions"))
387         {
388                 printf("Resolutions we think are okay:\n");
389                 for (int i = 0; resolutions[i]; i++)
390                         printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
391         }
392
393     Uint32 sdlflags = SDL_OPENGL;
394     if (!cmdline("windowed"))
395         sdlflags |= SDL_FULLSCREEN;
396
397     SDL_WM_SetCaption("Lugaru", "Lugaru");
398
399     SDL_ShowCursor(0);
400
401     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
402     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
403     
404     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
405     {
406         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
407         fprintf(stderr, "forcing 640x480...\n");
408         kContextWidth = 640;
409         kContextHeight = 480;
410         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
411         {
412             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
413             fprintf(stderr, "forcing 640x480 windowed mode...\n");
414             sdlflags &= ~SDL_FULLSCREEN;
415             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
416             {
417                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
418                 return false;
419             }
420         }
421     }
422
423     int dblbuf = 0;
424     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
425     {
426         fprintf(stderr, "Failed to get double buffered GL context!\n");
427         SDL_Quit();
428         return false;
429     }
430
431     if (!lookup_all_glsyms())
432     {
433         SDL_Quit();
434         return false;
435     }
436
437     if (!cmdline("nomousegrab"))
438         SDL_WM_GrabInput(SDL_GRAB_ON);
439
440
441         glClear( GL_COLOR_BUFFER_BIT );
442         swap_gl_buffers();
443
444         // clear all states
445         glDisable( GL_ALPHA_TEST);
446         glDisable( GL_BLEND);
447         glDisable( GL_DEPTH_TEST);
448         //      glDisable( GL_DITHER);
449         glDisable( GL_FOG);
450         glDisable( GL_LIGHTING);
451         glDisable( GL_LOGIC_OP);
452         glDisable( GL_TEXTURE_1D);
453         glDisable( GL_TEXTURE_2D);
454         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
455         glPixelTransferi( GL_RED_SCALE, 1);
456         glPixelTransferi( GL_RED_BIAS, 0);
457         glPixelTransferi( GL_GREEN_SCALE, 1);
458         glPixelTransferi( GL_GREEN_BIAS, 0);
459         glPixelTransferi( GL_BLUE_SCALE, 1);
460         glPixelTransferi( GL_BLUE_BIAS, 0);
461         glPixelTransferi( GL_ALPHA_SCALE, 1);
462         glPixelTransferi( GL_ALPHA_BIAS, 0);
463
464         // set initial rendering states
465         glShadeModel( GL_SMOOTH);
466         glClearDepth( 1.0f);
467         glDepthFunc( GL_LEQUAL);
468         glDepthMask( GL_TRUE);
469         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
470         glEnable( GL_DEPTH_TEST);
471         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
472         glCullFace( GL_FRONT);
473         glEnable( GL_CULL_FACE);
474         glEnable( GL_LIGHTING);
475 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
476         glEnable( GL_DITHER);
477         glEnable( GL_COLOR_MATERIAL);
478         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
479         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
480         glAlphaFunc( GL_GREATER, 0.5f);
481
482         GLint width = kContextWidth;
483         GLint height = kContextHeight;
484         gMidPoint.h = width / 2;
485         gMidPoint.v = height / 2;
486         screenwidth=width;
487         screenheight=height;
488
489         game.newdetail=detail;
490         game.newscreenwidth=screenwidth;
491         game.newscreenheight=screenheight;
492
493         if ( CanInitStereo(stereomode) ) {
494                 InitStereo(stereomode);
495         } else {
496                 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
497                 stereomode = stereoNone;
498         }
499
500         game.InitGame();
501
502         return true;
503 }
504
505
506 static void DoMouse(Game & game)
507 {
508
509         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
510         {
511                 game.deltah *= usermousesensitivity;
512                 game.deltav *= usermousesensitivity;
513                 game.mousecoordh += game.deltah;
514                 game.mousecoordv += game.deltav;
515         if (game.mousecoordh < 0)
516             game.mousecoordh = 0;
517         else if (game.mousecoordh >= kContextWidth)
518             game.mousecoordh = kContextWidth - 1;
519         if (game.mousecoordv < 0)
520             game.mousecoordv = 0;
521         else if (game.mousecoordv >= kContextHeight)
522             game.mousecoordv = kContextHeight - 1;
523         }
524
525 }
526
527 void DoFrameRate (int update)
528 {       
529         static long frames = 0;
530
531         static AbsoluteTime time = {0,0};
532         static AbsoluteTime frametime = {0,0};
533         AbsoluteTime currTime = UpTime ();
534         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
535
536         if (0 > deltaTime)      // if negative microseconds
537                 deltaTime /= -1000000.0;
538         else                            // else milliseconds
539                 deltaTime /= 1000.0;
540
541         multiplier=deltaTime;
542         if(multiplier<.001) multiplier=.001;
543         if(multiplier>10) multiplier=10;
544         if(update) frametime = currTime;        // reset for next time interval
545
546         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
547
548         if (0 > deltaTime)      // if negative microseconds
549                 deltaTime /= -1000000.0;
550         else                            // else milliseconds
551                 deltaTime /= 1000.0;
552         frames++;
553         if (0.001 <= deltaTime) // has update interval passed
554         {
555                 if(update){
556                         time = currTime;        // reset for next time interval
557                         frames = 0;
558                 }
559         }
560 }
561
562
563 void DoUpdate (Game & game)
564 {
565         static float sps=200;
566         static int count;
567         static float oldmult;
568
569         DoFrameRate(1);
570         if(multiplier>.6)multiplier=.6;
571
572         game.fps=1/multiplier;
573
574         count = multiplier*sps;
575         if(count<2)count=2;
576         //if(count>10)count=10;
577
578         realmultiplier=multiplier;
579         multiplier*=gamespeed;
580         if(difficulty==1)multiplier*=.9;
581         if(difficulty==0)multiplier*=.8;
582
583         if(game.loading==4)multiplier*=.00001;
584         //multiplier*.9;
585         if(slomo&&!mainmenu)multiplier*=slomospeed;
586         //if(freeze)multiplier*=0.00001;
587         oldmult=multiplier;
588         multiplier/=(float)count;
589
590         DoMouse(game);
591
592         game.TickOnce();
593
594         for(int i=0;i<count;i++)
595         {
596                 game.Tick();
597         }
598         multiplier=oldmult;
599
600         game.TickOnceAfter();
601 /* - Debug code to test how many channels were active on average per frame
602         static long frames = 0;
603
604         static AbsoluteTime start = {0,0};
605         AbsoluteTime currTime = UpTime ();
606         static int num_channels = 0;
607         
608         num_channels += OPENAL_GetChannelsPlaying();
609         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
610
611         if (0 > deltaTime)      // if negative microseconds
612                 deltaTime /= -1000000.0;
613         else                            // else milliseconds
614                 deltaTime /= 1000.0;
615
616         ++frames;
617
618         if (deltaTime >= 1)
619         {
620                 start = currTime;
621                 float avg_channels = (float)num_channels / (float)frames;
622
623                 ofstream opstream("log.txt",ios::app); 
624                 opstream << "Average frame count: ";
625                 opstream << frames;
626                 opstream << " frames - ";
627                 opstream << avg_channels;
628                 opstream << " per frame.\n";
629                 opstream.close();
630
631                 frames = 0;
632                 num_channels = 0;
633         }
634 */
635         DrawGL (game);
636 }
637
638 // --------------------------------------------------------------------------
639
640
641 void CleanUp (void)
642 {
643         LOGFUNC;
644
645 //      game.Dispose();
646
647
648
649
650     SDL_Quit();
651     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
652     #include "glstubs.h"
653     #undef GL_FUNC
654     // cheat here...static destructors are calling glDeleteTexture() after
655     //  the context is destroyed and libGL unloaded by SDL_Quit().
656     pglDeleteTextures = glDeleteTextures_doNothing;
657
658 }
659
660 // --------------------------------------------------------------------------
661
662 static bool IsFocused()
663 {
664     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
665 }
666
667
668 static void launch_web_browser(const char *url)
669 {
670 #ifdef WIN32
671     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
672
673 #elif (defined(__APPLE__) && defined(__MACH__))
674     const char *fmt = "open '%s'";
675     const size_t len = strlen(fmt) + strlen(url) + 16;
676     char *buf = new char[len];
677     snprintf(buf, len, fmt, url);
678     system(buf);
679     delete[] buf;
680
681 #elif PLATFORM_LINUX
682     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
683     const size_t len = strlen(fmt) + strlen(url) + 16;
684     char *buf = new char[len];
685     snprintf(buf, len, fmt, url);
686     system(buf);
687     delete[] buf;
688 #endif
689 }
690
691
692 #ifndef WIN32
693 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
694 static char *findBinaryInPath(const char *bin, char *envr)
695 {
696     size_t alloc_size = 0;
697     char *exe = NULL;
698     char *start = envr;
699     char *ptr;
700
701     do
702     {
703         size_t size;
704         ptr = strchr(start, ':');  /* find next $PATH separator. */
705         if (ptr)
706             *ptr = '\0';
707
708         size = strlen(start) + strlen(bin) + 2;
709         if (size > alloc_size)
710         {
711             char *x = (char *) realloc(exe, size);
712             if (x == NULL)
713             {
714                 if (exe != NULL)
715                     free(exe);
716                 return(NULL);
717             } /* if */
718
719             alloc_size = size;
720             exe = x;
721         } /* if */
722
723         /* build full binary path... */
724         strcpy(exe, start);
725         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
726             strcat(exe, "/");
727         strcat(exe, bin);
728
729         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
730         {
731             strcpy(exe, start);  /* i'm lazy. piss off. */
732             return(exe);
733         } /* if */
734
735         start = ptr + 1;  /* start points to beginning of next element. */
736     } while (ptr != NULL);
737
738     if (exe != NULL)
739         free(exe);
740
741     return(NULL);  /* doesn't exist in path. */
742 } /* findBinaryInPath */
743
744
745 char *calcBaseDir(const char *argv0)
746 {
747     /* If there isn't a path on argv0, then look through the $PATH for it. */
748     char *retval;
749     char *envr;
750
751     const char *ptr = strrchr((char *)argv0, '/');
752     if (strchr(argv0, '/'))
753     {
754         retval = strdup(argv0);
755         if (retval)
756             *((char *) strrchr(retval, '/')) = '\0';
757         return(retval);
758     }
759
760     envr = getenv("PATH");
761     if (!envr) return NULL;
762     envr = strdup(envr);
763     if (!envr) return NULL;
764     retval = findBinaryInPath(argv0, envr);
765     free(envr);
766     return(retval);
767 }
768
769 static inline void chdirToAppPath(const char *argv0)
770 {
771     char *dir = calcBaseDir(argv0);
772     if (dir)
773     {
774         #if (defined(__APPLE__) && defined(__MACH__))
775         // Chop off /Contents/MacOS if it's at the end of the string, so we
776         //  land in the base of the app bundle.
777         const size_t len = strlen(dir);
778         const char *bundledirs = "/Contents/MacOS";
779         const size_t bundledirslen = strlen(bundledirs);
780         if (len > bundledirslen)
781         {
782             char *ptr = (dir + len) - bundledirslen;
783             if (strcasecmp(ptr, bundledirs) == 0)
784                 *ptr = '\0';
785         }
786         #endif
787         chdir(dir);
788         free(dir);
789     }
790 }
791 #endif
792
793
794 int main(int argc, char **argv)
795 {
796 #ifndef __MINGW32__
797     _argc = argc;
798     _argv = argv;
799 #endif
800
801     // !!! FIXME: we could use a Win32 API for this.  --ryan.
802 #ifndef WIN32
803     chdirToAppPath(argv[0]);
804 #endif
805
806         LOGFUNC;
807
808         //memset( &g_theKeys, 0, sizeof( KeyMap));
809
810     //initSDLKeyTable();
811
812         try
813         {
814                 bool regnow = false;
815                 {
816                         Game game;
817                         pgame = &game;
818
819                         //ofstream os("error.txt");
820                         //os.close();
821                         //ofstream os("log.txt");
822                         //os.close();
823
824                         if (!SetUp (game))
825                 return 42;
826
827                         while (!gDone&&!game.quit&&(!game.tryquit))
828                         {
829                                 if (IsFocused())
830                                 {
831                                         gameFocused = true;
832
833                                         // check windows messages
834                         
835                                         game.deltah = 0;
836                                         game.deltav = 0;
837                                         SDL_Event e;
838                                         if(!game.isWaiting()) {
839                                                 // message pump
840                                                 while( SDL_PollEvent( &e ) )
841                                                 {
842                                                         if( e.type == SDL_QUIT )
843                                                         {
844                                                                 gDone=true;
845                                                                 break;
846                                                         }
847                                                         sdlEventProc(e, game);
848                                                 }
849                                         }
850
851                                         // game
852                                         DoUpdate(game);
853                                 }
854                                 else
855                                 {
856                                         if (gameFocused)
857                                         {
858                                                 // allow game chance to pause
859                                                 gameFocused = false;
860                                                 DoUpdate(game);
861                                         }
862
863                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
864                                         SDL_ActiveEvent evt;
865                                         SDL_WaitEvent((SDL_Event*)&evt);
866                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
867                                                 gameFocused = true;
868                                         else if (evt.type == SDL_QUIT)
869                                                 gDone = true;
870                                 }
871                         }
872
873                         regnow = game.registernow;
874                 }
875                 pgame = 0;
876
877                 CleanUp ();
878                 
879                 return 0;
880         }
881         catch (const std::exception& error)
882         {
883                 CleanUp();
884
885                 std::string e = "Caught exception: ";
886                 e += error.what();
887
888                 LOG(e);
889
890                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
891         }
892
893         CleanUp();
894
895         return -1;
896 }
897
898
899
900         // --------------------------------------------------------------------------
901
902         extern int channels[100];
903         extern OPENAL_SAMPLE * samp[100];
904         extern OPENAL_STREAM * strm[20];
905
906         extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
907         {
908                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
909                 if (currSample && currSample == samp[chan])
910                 {
911                         if (OPENAL_GetPaused(channels[chan]))
912                         {
913                                 OPENAL_StopSound(channels[chan]);
914                                 channels[chan] = OPENAL_FREE;
915                         }
916                         else if (OPENAL_IsPlaying(channels[chan]))
917                         {
918                                 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
919                                 if (loop_mode & OPENAL_LOOP_OFF)
920                                 {
921                                         channels[chan] = OPENAL_FREE;
922                                 }
923                         }
924                 }
925                 else
926                 {
927                         channels[chan] = OPENAL_FREE;
928                 }
929
930                 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
931                 if (channels[chan] < 0)
932                 {
933                         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
934                 }
935         }
936
937         extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
938         {
939                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
940                 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
941                 {
942                                 OPENAL_StopSound(channels[chan]);
943                                 OPENAL_Stream_Stop(sptr);
944                 }
945                 else
946                 {
947                         OPENAL_Stream_Stop(sptr);
948                         channels[chan] = OPENAL_FREE;
949                 }
950
951                 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
952                 if (channels[chan] < 0)
953                 {
954                         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
955                 }
956         }
957
958
959         bool LoadImage(const char * fname, TGAImageRec & tex)
960         {
961                 if ( tex.data == NULL )
962                         return false;
963                 else
964                         return load_image(fname, tex);
965         }
966
967         void ScreenShot(const char * fname)
968         {
969         save_image(fname);
970         }
971
972
973
974 static bool load_image(const char *file_name, TGAImageRec &tex)
975 {
976     const char *ptr = strrchr((char *)file_name, '.');
977     if (ptr)
978     {
979         if (strcasecmp(ptr+1, "png") == 0)
980             return load_png(file_name, tex);
981         else if (strcasecmp(ptr+1, "jpg") == 0)
982             return load_jpg(file_name, tex);
983     }
984
985     STUBBED("Unsupported image type");
986     return false;
987 }
988
989
990 struct my_error_mgr {
991   struct jpeg_error_mgr pub;    /* "public" fields */
992   jmp_buf setjmp_buffer;        /* for return to caller */
993 };
994 typedef struct my_error_mgr * my_error_ptr;
995
996
997 static void my_error_exit(j_common_ptr cinfo)
998 {
999         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1000         longjmp(err->setjmp_buffer, 1);
1001 }
1002
1003 /* stolen from public domain example.c code in libjpg distribution. */
1004 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1005 {
1006     struct jpeg_decompress_struct cinfo;
1007     struct my_error_mgr jerr;
1008     JSAMPROW buffer[1];         /* Output row buffer */
1009     int row_stride;             /* physical row width in output buffer */
1010     FILE *infile = fopen(file_name, "rb");
1011
1012     if (infile == NULL)
1013         return false;
1014
1015     cinfo.err = jpeg_std_error(&jerr.pub);
1016     jerr.pub.error_exit = my_error_exit;
1017     if (setjmp(jerr.setjmp_buffer)) {
1018         jpeg_destroy_decompress(&cinfo);
1019         fclose(infile);
1020         return false;
1021     }
1022
1023     jpeg_create_decompress(&cinfo);
1024     jpeg_stdio_src(&cinfo, infile);
1025     (void) jpeg_read_header(&cinfo, TRUE);
1026
1027     cinfo.out_color_space = JCS_RGB;
1028     cinfo.quantize_colors = 0;
1029     (void) jpeg_calc_output_dimensions(&cinfo);
1030     (void) jpeg_start_decompress(&cinfo);
1031
1032     row_stride = cinfo.output_width * cinfo.output_components;
1033     tex.sizeX = cinfo.output_width;
1034     tex.sizeY = cinfo.output_height;
1035     tex.bpp = 24;
1036
1037     while (cinfo.output_scanline < cinfo.output_height) {
1038         buffer[0] = (JSAMPROW)(char *)tex.data +
1039                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1040         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1041     }
1042
1043     (void) jpeg_finish_decompress(&cinfo);
1044     jpeg_destroy_decompress(&cinfo);
1045     fclose(infile);
1046
1047     return true;
1048 }
1049
1050
1051 /* stolen from public domain example.c code in libpng distribution. */
1052 static bool load_png(const char *file_name, TGAImageRec &tex)
1053 {
1054     bool hasalpha = false;
1055     png_structp png_ptr = NULL;
1056     png_infop info_ptr = NULL;
1057     png_uint_32 width, height;
1058     int bit_depth, color_type, interlace_type;
1059     png_byte **rows = NULL;
1060     bool retval = false;
1061     png_byte **row_pointers = NULL;
1062     FILE *fp = fopen(file_name, "rb");
1063
1064     if (fp == NULL)
1065         return(NULL);
1066
1067     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1068     if (png_ptr == NULL)
1069         goto png_done;
1070
1071     info_ptr = png_create_info_struct(png_ptr);
1072     if (info_ptr == NULL)
1073         goto png_done;
1074
1075     if (setjmp(png_jmpbuf(png_ptr)))
1076         goto png_done;
1077
1078     png_init_io(png_ptr, fp);
1079     png_read_png(png_ptr, info_ptr,
1080                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1081                  NULL);
1082     png_get_IHDR(png_ptr, info_ptr, &width, &height,
1083                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
1084
1085     if (bit_depth != 8)  // transform SHOULD handle this...
1086         goto png_done;
1087
1088     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
1089         goto png_done;
1090
1091     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
1092         goto png_done;
1093
1094     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1095     row_pointers = png_get_rows(png_ptr, info_ptr);
1096     if (!row_pointers)
1097         goto png_done;
1098
1099     if (!hasalpha)
1100     {
1101         png_byte *dst = tex.data;
1102         for (int i = height-1; i >= 0; i--)
1103         {
1104             png_byte *src = row_pointers[i];
1105             for (int j = 0; j < width; j++)
1106             {
1107                 dst[0] = src[0];
1108                 dst[1] = src[1];
1109                 dst[2] = src[2];
1110                 dst[3] = 0xFF;
1111                 src += 3;
1112                 dst += 4;
1113             }
1114         }
1115     }
1116
1117     else
1118     {
1119         png_byte *dst = tex.data;
1120         int pitch = width * 4;
1121         for (int i = height-1; i >= 0; i--, dst += pitch)
1122             memcpy(dst, row_pointers[i], pitch);
1123     }
1124
1125     tex.sizeX = width;
1126     tex.sizeY = height;
1127     tex.bpp = 32;
1128     retval = true;
1129
1130 png_done:
1131     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1132     if (fp)
1133         fclose(fp);
1134     return (retval);
1135 }
1136
1137
1138 static bool save_image(const char *file_name)
1139 {
1140     const char *ptr = strrchr((char *)file_name, '.');
1141     if (ptr)
1142     {
1143         if (strcasecmp(ptr+1, "png") == 0)
1144             return save_png(file_name);
1145     }
1146
1147     STUBBED("Unsupported image type");
1148     return false;
1149 }
1150
1151
1152 static bool save_png(const char *file_name)
1153 {
1154     FILE *fp = NULL;
1155     png_structp png_ptr = NULL;
1156     png_infop info_ptr = NULL;
1157     bool retval = false;
1158
1159     fp = fopen(file_name, "wb");
1160     if (fp == NULL)
1161         return false;
1162
1163     png_bytep *row_pointers = new png_bytep[kContextHeight];
1164     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1165     if ((!screenshot) || (!row_pointers))
1166         goto save_png_done;
1167
1168     glGetError();
1169     glReadPixels(0, 0, kContextWidth, kContextHeight,
1170                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1171     if (glGetError() != GL_NO_ERROR)
1172         goto save_png_done;
1173
1174     for (int i = 0; i < kContextHeight; i++)
1175         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1176
1177     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1178     if (png_ptr == NULL)
1179         goto save_png_done;
1180
1181     info_ptr = png_create_info_struct(png_ptr);
1182     if (info_ptr == NULL)
1183         goto save_png_done;
1184
1185     if (setjmp(png_jmpbuf(png_ptr)))
1186         goto save_png_done;
1187
1188     png_init_io(png_ptr, fp);
1189
1190     if (setjmp(png_jmpbuf(png_ptr)))
1191         goto save_png_done;
1192
1193     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1194                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1195                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1196
1197     png_write_info(png_ptr, info_ptr);
1198
1199     if (setjmp(png_jmpbuf(png_ptr)))
1200         goto save_png_done;
1201
1202         png_write_image(png_ptr, row_pointers);
1203
1204         if (setjmp(png_jmpbuf(png_ptr)))
1205         goto save_png_done;
1206
1207     png_write_end(png_ptr, NULL);
1208     retval = true;
1209
1210 save_png_done:
1211     png_destroy_write_struct(&png_ptr, &info_ptr);
1212     delete[] screenshot;
1213     delete[] row_pointers;
1214     if (fp)
1215         fclose(fp);
1216     if (!retval)
1217         unlink(ConvertFileName(file_name));
1218     return retval;
1219 }
1220
1221
1222