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