]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Missing files in the CMakeList.txt
[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
486         realmultiplier=multiplier;
487         multiplier*=gamespeed;
488         if(difficulty==1)multiplier*=.9;
489         if(difficulty==0)multiplier*=.8;
490
491         if(game.loading==4)multiplier*=.00001;
492         if(slomo&&!mainmenu)multiplier*=slomospeed;
493         oldmult=multiplier;
494         multiplier/=(float)count;
495
496         DoMouse(game);
497
498         game.TickOnce();
499
500         for(int i=0;i<count;i++)
501         {
502                 game.Tick();
503         }
504         multiplier=oldmult;
505
506         game.TickOnceAfter();
507 /* - Debug code to test how many channels were active on average per frame
508         static long frames = 0;
509
510         static AbsoluteTime start = {0,0};
511         AbsoluteTime currTime = UpTime ();
512         static int num_channels = 0;
513         
514         num_channels += OPENAL_GetChannelsPlaying();
515         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
516
517         if (0 > deltaTime)      // if negative microseconds
518                 deltaTime /= -1000000.0;
519         else                            // else milliseconds
520                 deltaTime /= 1000.0;
521
522         ++frames;
523
524         if (deltaTime >= 1)
525         {
526                 start = currTime;
527                 float avg_channels = (float)num_channels / (float)frames;
528
529                 ofstream opstream("log.txt",ios::app); 
530                 opstream << "Average frame count: ";
531                 opstream << frames;
532                 opstream << " frames - ";
533                 opstream << avg_channels;
534                 opstream << " per frame.\n";
535                 opstream.close();
536
537                 frames = 0;
538                 num_channels = 0;
539         }
540 */
541         game.DrawGL();
542 }
543
544 // --------------------------------------------------------------------------
545
546
547 void CleanUp (void)
548 {
549         LOGFUNC;
550
551     SDL_Quit();
552     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
553     #include "glstubs.h"
554     #undef GL_FUNC
555     // cheat here...static destructors are calling glDeleteTexture() after
556     //  the context is destroyed and libGL unloaded by SDL_Quit().
557     pglDeleteTextures = glDeleteTextures_doNothing;
558
559 }
560
561 // --------------------------------------------------------------------------
562
563 static bool IsFocused()
564 {
565     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
566 }
567
568
569 static void launch_web_browser(const char *url)
570 {
571 #ifdef WIN32
572     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
573
574 #elif (defined(__APPLE__) && defined(__MACH__))
575     const char *fmt = "open '%s'";
576     const size_t len = strlen(fmt) + strlen(url) + 16;
577     char *buf = new char[len];
578     snprintf(buf, len, fmt, url);
579     system(buf);
580     delete[] buf;
581
582 #elif PLATFORM_LINUX
583     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
584     const size_t len = strlen(fmt) + strlen(url) + 16;
585     char *buf = new char[len];
586     snprintf(buf, len, fmt, url);
587     system(buf);
588     delete[] buf;
589 #endif
590 }
591
592
593 #ifndef WIN32
594 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
595 static char *findBinaryInPath(const char *bin, char *envr)
596 {
597     size_t alloc_size = 0;
598     char *exe = NULL;
599     char *start = envr;
600     char *ptr;
601
602     do
603     {
604         size_t size;
605         ptr = strchr(start, ':');  /* find next $PATH separator. */
606         if (ptr)
607             *ptr = '\0';
608
609         size = strlen(start) + strlen(bin) + 2;
610         if (size > alloc_size)
611         {
612             char *x = (char *) realloc(exe, size);
613             if (x == NULL)
614             {
615                 if (exe != NULL)
616                     free(exe);
617                 return(NULL);
618             } /* if */
619
620             alloc_size = size;
621             exe = x;
622         } /* if */
623
624         /* build full binary path... */
625         strcpy(exe, start);
626         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
627             strcat(exe, "/");
628         strcat(exe, bin);
629
630         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
631         {
632             strcpy(exe, start);  /* i'm lazy. piss off. */
633             return(exe);
634         } /* if */
635
636         start = ptr + 1;  /* start points to beginning of next element. */
637     } while (ptr != NULL);
638
639     if (exe != NULL)
640         free(exe);
641
642     return(NULL);  /* doesn't exist in path. */
643 } /* findBinaryInPath */
644
645
646 char *calcBaseDir(const char *argv0)
647 {
648     /* If there isn't a path on argv0, then look through the $PATH for it. */
649     char *retval;
650     char *envr;
651
652     const char *ptr = strrchr((char *)argv0, '/');
653     if (strchr(argv0, '/'))
654     {
655         retval = strdup(argv0);
656         if (retval)
657             *((char *) strrchr(retval, '/')) = '\0';
658         return(retval);
659     }
660
661     envr = getenv("PATH");
662     if (!envr) return NULL;
663     envr = strdup(envr);
664     if (!envr) return NULL;
665     retval = findBinaryInPath(argv0, envr);
666     free(envr);
667     return(retval);
668 }
669
670 static inline void chdirToAppPath(const char *argv0)
671 {
672     char *dir = calcBaseDir(argv0);
673     if (dir)
674     {
675         #if (defined(__APPLE__) && defined(__MACH__))
676         // Chop off /Contents/MacOS if it's at the end of the string, so we
677         //  land in the base of the app bundle.
678         const size_t len = strlen(dir);
679         const char *bundledirs = "/Contents/MacOS";
680         const size_t bundledirslen = strlen(bundledirs);
681         if (len > bundledirslen)
682         {
683             char *ptr = (dir + len) - bundledirslen;
684             if (strcasecmp(ptr, bundledirs) == 0)
685                 *ptr = '\0';
686         }
687         #endif
688         chdir(dir);
689         free(dir);
690     }
691 }
692 #endif
693
694
695 int main(int argc, char **argv)
696 {
697 #ifndef __MINGW32__
698     _argc = argc;
699     _argv = argv;
700 #endif
701
702     // !!! FIXME: we could use a Win32 API for this.  --ryan.
703 #ifndef WIN32
704     chdirToAppPath(argv[0]);
705 #endif
706
707         LOGFUNC;
708
709         try
710         {
711                 bool regnow = false;
712                 {
713                         Game game;
714                         pgame = &game;
715
716                         //ofstream os("error.txt");
717                         //os.close();
718                         //ofstream os("log.txt");
719                         //os.close();
720
721                         if (!SetUp (game))
722                 return 42;
723
724                         while (!gDone&&!game.quit&&(!game.tryquit))
725                         {
726                                 if (IsFocused())
727                                 {
728                                         gameFocused = true;
729
730                                         // check windows messages
731                         
732                                         game.deltah = 0;
733                                         game.deltav = 0;
734                                         SDL_Event e;
735                                         if(!game.isWaiting()) {
736                                                 // message pump
737                                                 while( SDL_PollEvent( &e ) )
738                                                 {
739                                                         if( e.type == SDL_QUIT )
740                                                         {
741                                                                 gDone=true;
742                                                                 break;
743                                                         }
744                                                         sdlEventProc(e, game);
745                                                 }
746                                         }
747
748                                         // game
749                                         DoUpdate(game);
750                                 }
751                                 else
752                                 {
753                                         if (gameFocused)
754                                         {
755                                                 // allow game chance to pause
756                                                 gameFocused = false;
757                                                 DoUpdate(game);
758                                         }
759
760                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
761                                         SDL_ActiveEvent evt;
762                                         SDL_WaitEvent((SDL_Event*)&evt);
763                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
764                                                 gameFocused = true;
765                                         else if (evt.type == SDL_QUIT)
766                                                 gDone = true;
767                                 }
768                         }
769
770                         regnow = game.registernow;
771                 }
772                 pgame = 0;
773
774                 CleanUp ();
775                 
776                 return 0;
777         }
778         catch (const std::exception& error)
779         {
780                 CleanUp();
781
782                 std::string e = "Caught exception: ";
783                 e += error.what();
784
785                 LOG(e);
786
787                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
788         }
789
790         CleanUp();
791
792         return -1;
793 }
794
795
796
797 // --------------------------------------------------------------------------
798
799 extern int channels[100];
800 extern OPENAL_SAMPLE * samp[100];
801 extern OPENAL_STREAM * strm[20];
802
803 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
804 {
805         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
806         if (currSample && currSample == samp[chan])
807         {
808                 if (OPENAL_GetPaused(channels[chan]))
809                 {
810                         OPENAL_StopSound(channels[chan]);
811                         channels[chan] = OPENAL_FREE;
812                 }
813                 else if (OPENAL_IsPlaying(channels[chan]))
814                 {
815                         int loop_mode = OPENAL_GetLoopMode(channels[chan]);
816                         if (loop_mode & OPENAL_LOOP_OFF)
817                         {
818                                 channels[chan] = OPENAL_FREE;
819                         }
820                 }
821         }
822         else
823         {
824                 channels[chan] = OPENAL_FREE;
825         }
826
827         channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
828         if (channels[chan] < 0)
829         {
830                 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
831         }
832 }
833
834 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
835 {
836         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
837         if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
838         {
839                         OPENAL_StopSound(channels[chan]);
840                         OPENAL_Stream_Stop(sptr);
841         }
842         else
843         {
844                 OPENAL_Stream_Stop(sptr);
845                 channels[chan] = OPENAL_FREE;
846         }
847
848         channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
849         if (channels[chan] < 0)
850         {
851                 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
852         }
853 }
854
855
856 bool LoadImage(const char * fname, TGAImageRec & tex)
857 {
858         if ( tex.data == NULL )
859                 return false;
860         else
861                 return load_image(fname, tex);
862 }
863
864 void ScreenShot(const char * fname)
865 {
866         
867 }
868
869
870
871 static bool load_image(const char *file_name, TGAImageRec &tex)
872 {
873     const char *ptr = strrchr((char *)file_name, '.');
874     if (ptr)
875     {
876         if (strcasecmp(ptr+1, "png") == 0)
877             return load_png(file_name, tex);
878         else if (strcasecmp(ptr+1, "jpg") == 0)
879             return load_jpg(file_name, tex);
880     }
881
882     STUBBED("Unsupported image type");
883     return false;
884 }
885
886
887 struct my_error_mgr {
888   struct jpeg_error_mgr pub;    /* "public" fields */
889   jmp_buf setjmp_buffer;        /* for return to caller */
890 };
891 typedef struct my_error_mgr * my_error_ptr;
892
893
894 static void my_error_exit(j_common_ptr cinfo)
895 {
896         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
897         longjmp(err->setjmp_buffer, 1);
898 }
899
900 /* stolen from public domain example.c code in libjpg distribution. */
901 static bool load_jpg(const char *file_name, TGAImageRec &tex)
902 {
903     struct jpeg_decompress_struct cinfo;
904     struct my_error_mgr jerr;
905     JSAMPROW buffer[1];         /* Output row buffer */
906     int row_stride;             /* physical row width in output buffer */
907     FILE *infile = fopen(file_name, "rb");
908
909     if (infile == NULL)
910         return false;
911
912     cinfo.err = jpeg_std_error(&jerr.pub);
913     jerr.pub.error_exit = my_error_exit;
914     if (setjmp(jerr.setjmp_buffer)) {
915         jpeg_destroy_decompress(&cinfo);
916         fclose(infile);
917         return false;
918     }
919
920     jpeg_create_decompress(&cinfo);
921     jpeg_stdio_src(&cinfo, infile);
922     (void) jpeg_read_header(&cinfo, TRUE);
923
924     cinfo.out_color_space = JCS_RGB;
925     cinfo.quantize_colors = 0;
926     (void) jpeg_calc_output_dimensions(&cinfo);
927     (void) jpeg_start_decompress(&cinfo);
928
929     row_stride = cinfo.output_width * cinfo.output_components;
930     tex.sizeX = cinfo.output_width;
931     tex.sizeY = cinfo.output_height;
932     tex.bpp = 24;
933
934     while (cinfo.output_scanline < cinfo.output_height) {
935         buffer[0] = (JSAMPROW)(char *)tex.data +
936                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
937         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
938     }
939
940     (void) jpeg_finish_decompress(&cinfo);
941     jpeg_destroy_decompress(&cinfo);
942     fclose(infile);
943
944     return true;
945 }
946
947
948 /* stolen from public domain example.c code in libpng distribution. */
949 static bool load_png(const char *file_name, TGAImageRec &tex)
950 {
951     bool hasalpha = false;
952     png_structp png_ptr = NULL;
953     png_infop info_ptr = NULL;
954     png_uint_32 width, height;
955     int bit_depth, color_type, interlace_type;
956     png_byte **rows = NULL;
957     bool retval = false;
958     png_byte **row_pointers = NULL;
959     FILE *fp = fopen(file_name, "rb");
960
961     if (fp == NULL)
962         return(NULL);
963
964     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
965     if (png_ptr == NULL)
966         goto png_done;
967
968     info_ptr = png_create_info_struct(png_ptr);
969     if (info_ptr == NULL)
970         goto png_done;
971
972     if (setjmp(png_jmpbuf(png_ptr)))
973         goto png_done;
974
975     png_init_io(png_ptr, fp);
976     png_read_png(png_ptr, info_ptr,
977                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
978                  NULL);
979     png_get_IHDR(png_ptr, info_ptr, &width, &height,
980                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
981
982     if (bit_depth != 8)  // transform SHOULD handle this...
983         goto png_done;
984
985     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
986         goto png_done;
987
988     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
989         goto png_done;
990
991     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
992     row_pointers = png_get_rows(png_ptr, info_ptr);
993     if (!row_pointers)
994         goto png_done;
995
996     if (!hasalpha)
997     {
998         png_byte *dst = tex.data;
999         for (int i = height-1; i >= 0; i--)
1000         {
1001             png_byte *src = row_pointers[i];
1002             for (int j = 0; j < width; j++)
1003             {
1004                 dst[0] = src[0];
1005                 dst[1] = src[1];
1006                 dst[2] = src[2];
1007                 dst[3] = 0xFF;
1008                 src += 3;
1009                 dst += 4;
1010             }
1011         }
1012     }
1013
1014     else
1015     {
1016         png_byte *dst = tex.data;
1017         int pitch = width * 4;
1018         for (int i = height-1; i >= 0; i--, dst += pitch)
1019             memcpy(dst, row_pointers[i], pitch);
1020     }
1021
1022     tex.sizeX = width;
1023     tex.sizeY = height;
1024     tex.bpp = 32;
1025     retval = true;
1026
1027 png_done:
1028     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1029     if (fp)
1030         fclose(fp);
1031     return (retval);
1032 }
1033
1034
1035 bool save_image(const char *file_name)
1036 {
1037     const char *ptr = strrchr((char *)file_name, '.');
1038     if (ptr)
1039     {
1040         if (strcasecmp(ptr+1, "png") == 0)
1041             return save_png(file_name);
1042     }
1043
1044     STUBBED("Unsupported image type");
1045     return false;
1046 }
1047
1048
1049 static bool save_png(const char *file_name)
1050 {
1051     FILE *fp = NULL;
1052     png_structp png_ptr = NULL;
1053     png_infop info_ptr = NULL;
1054     bool retval = false;
1055
1056     fp = fopen(file_name, "wb");
1057     if (fp == NULL)
1058         return false;
1059
1060     png_bytep *row_pointers = new png_bytep[kContextHeight];
1061     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1062     if ((!screenshot) || (!row_pointers))
1063         goto save_png_done;
1064
1065     glGetError();
1066     glReadPixels(0, 0, kContextWidth, kContextHeight,
1067                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1068     if (glGetError() != GL_NO_ERROR)
1069         goto save_png_done;
1070
1071     for (int i = 0; i < kContextHeight; i++)
1072         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1073
1074     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1075     if (png_ptr == NULL)
1076         goto save_png_done;
1077
1078     info_ptr = png_create_info_struct(png_ptr);
1079     if (info_ptr == NULL)
1080         goto save_png_done;
1081
1082     if (setjmp(png_jmpbuf(png_ptr)))
1083         goto save_png_done;
1084
1085     png_init_io(png_ptr, fp);
1086
1087     if (setjmp(png_jmpbuf(png_ptr)))
1088         goto save_png_done;
1089
1090     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1091                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1092                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1093
1094     png_write_info(png_ptr, info_ptr);
1095
1096     if (setjmp(png_jmpbuf(png_ptr)))
1097         goto save_png_done;
1098
1099         png_write_image(png_ptr, row_pointers);
1100
1101         if (setjmp(png_jmpbuf(png_ptr)))
1102         goto save_png_done;
1103
1104     png_write_end(png_ptr, NULL);
1105     retval = true;
1106
1107 save_png_done:
1108     png_destroy_write_struct(&png_ptr, &info_ptr);
1109     delete[] screenshot;
1110     delete[] row_pointers;
1111     if (fp)
1112         fclose(fp);
1113     if (!retval)
1114         unlink(ConvertFileName(file_name));
1115     return retval;
1116 }
1117
1118
1119