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