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