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