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