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