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