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