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