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