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