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