]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
a0ace20b7ac291148281b2d202ae3841fc8c20bb
[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) multiplier = .001;
456     if (multiplier > 10) multiplier = 10;
457     if (update) 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)multiplier = .6;
483
484     fps = 1 / multiplier;
485
486     count = multiplier * sps;
487     if (count < 2)count = 2;
488
489     realmultiplier = multiplier;
490     multiplier *= gamespeed;
491     if (difficulty == 1)multiplier *= .9;
492     if (difficulty == 0)multiplier *= .8;
493
494     if (loading == 4)multiplier *= .00001;
495     if (slomo && !mainmenu)multiplier *= slomospeed;
496     oldmult = multiplier;
497     multiplier /= (float)count;
498
499     DoMouse();
500
501     TickOnce();
502
503     for (int i = 0; i < count; i++) {
504         Tick();
505     }
506     multiplier = oldmult;
507
508     TickOnceAfter();
509     /* - Debug code to test how many channels were active on average per frame
510         static long frames = 0;
511
512         static AbsoluteTime start = {0,0};
513         AbsoluteTime currTime = UpTime ();
514         static int num_channels = 0;
515
516         num_channels += OPENAL_GetChannelsPlaying();
517         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
518
519         if (0 > deltaTime)      // if negative microseconds
520                 deltaTime /= -1000000.0;
521         else                            // else milliseconds
522                 deltaTime /= 1000.0;
523
524         ++frames;
525
526         if (deltaTime >= 1)
527         {
528                 start = currTime;
529                 float avg_channels = (float)num_channels / (float)frames;
530
531                 ofstream opstream("log.txt",ios::app);
532                 opstream << "Average frame count: ";
533                 opstream << frames;
534                 opstream << " frames - ";
535                 opstream << avg_channels;
536                 opstream << " per frame.\n";
537                 opstream.close();
538
539                 frames = 0;
540                 num_channels = 0;
541         }
542     */
543     if ( stereomode == stereoNone ) {
544         DrawGLScene(stereoCenter);
545     } else {
546         DrawGLScene(stereoLeft);
547         DrawGLScene(stereoRight);
548     }
549 }
550
551 // --------------------------------------------------------------------------
552
553
554 void CleanUp (void)
555 {
556     LOGFUNC;
557
558     SDL_Quit();
559 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
560 #include "glstubs.h"
561 #undef GL_FUNC
562     // cheat here...static destructors are calling glDeleteTexture() after
563     //  the context is destroyed and libGL unloaded by SDL_Quit().
564     pglDeleteTextures = glDeleteTextures_doNothing;
565
566 }
567
568 // --------------------------------------------------------------------------
569
570 static bool IsFocused()
571 {
572     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
573 }
574
575
576
577 #ifndef WIN32
578 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
579 static char *findBinaryInPath(const char *bin, char *envr)
580 {
581     size_t alloc_size = 0;
582     char *exe = NULL;
583     char *start = envr;
584     char *ptr;
585
586     do {
587         size_t size;
588         ptr = strchr(start, ':');  /* find next $PATH separator. */
589         if (ptr)
590             *ptr = '\0';
591
592         size = strlen(start) + strlen(bin) + 2;
593         if (size > alloc_size) {
594             char *x = (char *) realloc(exe, size);
595             if (x == NULL) {
596                 if (exe != NULL)
597                     free(exe);
598                 return(NULL);
599             } /* if */
600
601             alloc_size = size;
602             exe = x;
603         } /* if */
604
605         /* build full binary path... */
606         strcpy(exe, start);
607         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
608             strcat(exe, "/");
609         strcat(exe, bin);
610
611         if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
612             strcpy(exe, start);  /* i'm lazy. piss off. */
613             return(exe);
614         } /* if */
615
616         start = ptr + 1;  /* start points to beginning of next element. */
617     } while (ptr != NULL);
618
619     if (exe != NULL)
620         free(exe);
621
622     return(NULL);  /* doesn't exist in path. */
623 } /* findBinaryInPath */
624
625
626 char *calcBaseDir(const char *argv0)
627 {
628     /* If there isn't a path on argv0, then look through the $PATH for it. */
629     char *retval;
630     char *envr;
631
632     const char *ptr = strrchr((char *)argv0, '/');
633     if (strchr(argv0, '/')) {
634         retval = strdup(argv0);
635         if (retval)
636             *((char *) strrchr(retval, '/')) = '\0';
637         return(retval);
638     }
639
640     envr = getenv("PATH");
641     if (!envr) return NULL;
642     envr = strdup(envr);
643     if (!envr) return NULL;
644     retval = findBinaryInPath(argv0, envr);
645     free(envr);
646     return(retval);
647 }
648
649 static inline void chdirToAppPath(const char *argv0)
650 {
651     char *dir = calcBaseDir(argv0);
652     if (dir) {
653 #if (defined(__APPLE__) && defined(__MACH__))
654         // Chop off /Contents/MacOS if it's at the end of the string, so we
655         //  land in the base of the app bundle.
656         const size_t len = strlen(dir);
657         const char *bundledirs = "/Contents/MacOS";
658         const size_t bundledirslen = strlen(bundledirs);
659         if (len > bundledirslen) {
660             char *ptr = (dir + len) - bundledirslen;
661             if (strcasecmp(ptr, bundledirs) == 0)
662                 *ptr = '\0';
663         }
664 #endif
665         chdir(dir);
666         free(dir);
667     }
668 }
669 #endif
670
671
672 int main(int argc, char **argv)
673 {
674 #ifndef __MINGW32__
675     _argc = argc;
676     _argv = argv;
677 #endif
678
679     // !!! FIXME: we could use a Win32 API for this.  --ryan.
680 #ifndef WIN32
681     chdirToAppPath(argv[0]);
682 #endif
683
684     LOGFUNC;
685
686     try {
687         {
688             newGame();
689
690             //ofstream os("error.txt");
691             //os.close();
692             //ofstream os("log.txt");
693             //os.close();
694
695             if (!SetUp ())
696                 return 42;
697
698             while (!gDone && !tryquit) {
699                 if (IsFocused()) {
700                     gameFocused = true;
701
702                     // check windows messages
703
704                     deltah = 0;
705                     deltav = 0;
706                     SDL_Event e;
707                     if (!waiting) {
708                         // message pump
709                         while ( SDL_PollEvent( &e ) ) {
710                             if ( e.type == SDL_QUIT ) {
711                                 gDone = true;
712                                 break;
713                             }
714                             sdlEventProc(e);
715                         }
716                     }
717
718                     // game
719                     DoUpdate();
720                 } else {
721                     if (gameFocused) {
722                         // allow game chance to pause
723                         gameFocused = false;
724                         DoUpdate();
725                     }
726
727                     // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
728                     SDL_ActiveEvent evt;
729                     SDL_WaitEvent((SDL_Event*)&evt);
730                     if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
731                         gameFocused = true;
732                     else if (evt.type == SDL_QUIT)
733                         gDone = true;
734                 }
735             }
736
737             deleteGame();
738         }
739
740         CleanUp ();
741
742         return 0;
743     } catch (const std::exception& error) {
744         CleanUp();
745
746         std::string e = "Caught exception: ";
747         e += error.what();
748
749         LOG(e);
750
751         MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
752     }
753
754     CleanUp();
755
756     return -1;
757 }
758
759
760
761 // --------------------------------------------------------------------------
762
763
764 bool LoadImage(const char * fname, TGAImageRec & tex)
765 {
766     if ( tex.data == NULL )
767         return false;
768     else
769         return load_image(fname, tex);
770 }
771
772 void ScreenShot(const char * fname)
773 {
774
775 }
776
777
778
779 static bool load_image(const char *file_name, TGAImageRec &tex)
780 {
781     const char *ptr = strrchr((char *)file_name, '.');
782     if (ptr) {
783         if (strcasecmp(ptr + 1, "png") == 0)
784             return load_png(file_name, tex);
785         else if (strcasecmp(ptr + 1, "jpg") == 0)
786             return load_jpg(file_name, tex);
787     }
788
789     STUBBED("Unsupported image type");
790     return false;
791 }
792
793
794 struct my_error_mgr {
795     struct jpeg_error_mgr pub;  /* "public" fields */
796     jmp_buf setjmp_buffer;      /* for return to caller */
797 };
798 typedef struct my_error_mgr * my_error_ptr;
799
800
801 static void my_error_exit(j_common_ptr cinfo)
802 {
803     struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
804     longjmp(err->setjmp_buffer, 1);
805 }
806
807 /* stolen from public domain example.c code in libjpg distribution. */
808 static bool load_jpg(const char *file_name, TGAImageRec &tex)
809 {
810     struct jpeg_decompress_struct cinfo;
811     struct my_error_mgr jerr;
812     JSAMPROW buffer[1];         /* Output row buffer */
813     int row_stride;             /* physical row width in output buffer */
814     FILE *infile = fopen(file_name, "rb");
815
816     if (infile == NULL)
817         return false;
818
819     cinfo.err = jpeg_std_error(&jerr.pub);
820     jerr.pub.error_exit = my_error_exit;
821     if (setjmp(jerr.setjmp_buffer)) {
822         jpeg_destroy_decompress(&cinfo);
823         fclose(infile);
824         return false;
825     }
826
827     jpeg_create_decompress(&cinfo);
828     jpeg_stdio_src(&cinfo, infile);
829     (void) jpeg_read_header(&cinfo, TRUE);
830
831     cinfo.out_color_space = JCS_RGB;
832     cinfo.quantize_colors = 0;
833     (void) jpeg_calc_output_dimensions(&cinfo);
834     (void) jpeg_start_decompress(&cinfo);
835
836     row_stride = cinfo.output_width * cinfo.output_components;
837     tex.sizeX = cinfo.output_width;
838     tex.sizeY = cinfo.output_height;
839     tex.bpp = 24;
840
841     while (cinfo.output_scanline < cinfo.output_height) {
842         buffer[0] = (JSAMPROW)(char *)tex.data +
843                     ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
844         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
845     }
846
847     (void) jpeg_finish_decompress(&cinfo);
848     jpeg_destroy_decompress(&cinfo);
849     fclose(infile);
850
851     return true;
852 }
853
854
855 /* stolen from public domain example.c code in libpng distribution. */
856 static bool load_png(const char *file_name, TGAImageRec &tex)
857 {
858     bool hasalpha = false;
859     png_structp png_ptr = NULL;
860     png_infop info_ptr = NULL;
861     png_uint_32 width, height;
862     int bit_depth, color_type, interlace_type;
863     png_byte **rows = NULL;
864     bool retval = false;
865     png_byte **row_pointers = NULL;
866     FILE *fp = fopen(file_name, "rb");
867
868     if (fp == NULL) {
869         cerr << file_name << " not found" << endl;
870         return(NULL);
871     }
872
873     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
874     if (png_ptr == NULL)
875         goto png_done;
876
877     info_ptr = png_create_info_struct(png_ptr);
878     if (info_ptr == NULL)
879         goto png_done;
880
881     if (setjmp(png_jmpbuf(png_ptr)))
882         goto png_done;
883
884     png_init_io(png_ptr, fp);
885     png_read_png(png_ptr, info_ptr,
886                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
887                  NULL);
888     png_get_IHDR(png_ptr, info_ptr, &width, &height,
889                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
890
891     if (bit_depth != 8)  // transform SHOULD handle this...
892         goto png_done;
893
894     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
895         goto png_done;
896
897     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
898         goto png_done;
899
900     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
901     row_pointers = png_get_rows(png_ptr, info_ptr);
902     if (!row_pointers)
903         goto png_done;
904
905     if (!hasalpha) {
906         png_byte *dst = tex.data;
907         for (int i = height - 1; i >= 0; i--) {
908             png_byte *src = row_pointers[i];
909             for (int j = 0; j < width; j++) {
910                 dst[0] = src[0];
911                 dst[1] = src[1];
912                 dst[2] = src[2];
913                 dst[3] = 0xFF;
914                 src += 3;
915                 dst += 4;
916             }
917         }
918     }
919
920     else {
921         png_byte *dst = tex.data;
922         int pitch = width * 4;
923         for (int i = height - 1; i >= 0; i--, dst += pitch)
924             memcpy(dst, row_pointers[i], pitch);
925     }
926
927     tex.sizeX = width;
928     tex.sizeY = height;
929     tex.bpp = 32;
930     retval = true;
931
932 png_done:
933     if (!retval) {
934         cerr << "There was a problem loading " << file_name << endl;
935     }
936     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
937     if (fp)
938         fclose(fp);
939     return (retval);
940 }
941
942
943 bool save_image(const char *file_name)
944 {
945     const char *ptr = strrchr((char *)file_name, '.');
946     if (ptr) {
947         if (strcasecmp(ptr + 1, "png") == 0)
948             return save_png(file_name);
949     }
950
951     STUBBED("Unsupported image type");
952     return false;
953 }
954
955
956 static bool save_png(const char *file_name)
957 {
958     FILE *fp = NULL;
959     png_structp png_ptr = NULL;
960     png_infop info_ptr = NULL;
961     bool retval = false;
962
963     fp = fopen(file_name, "wb");
964     if (fp == NULL)
965         return false;
966
967     png_bytep *row_pointers = new png_bytep[kContextHeight];
968     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
969     if ((!screenshot) || (!row_pointers))
970         goto save_png_done;
971
972     glGetError();
973     glReadPixels(0, 0, kContextWidth, kContextHeight,
974                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
975     if (glGetError() != GL_NO_ERROR)
976         goto save_png_done;
977
978     for (int i = 0; i < kContextHeight; i++)
979         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
980
981     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
982     if (png_ptr == NULL)
983         goto save_png_done;
984
985     info_ptr = png_create_info_struct(png_ptr);
986     if (info_ptr == NULL)
987         goto save_png_done;
988
989     if (setjmp(png_jmpbuf(png_ptr)))
990         goto save_png_done;
991
992     png_init_io(png_ptr, fp);
993
994     if (setjmp(png_jmpbuf(png_ptr)))
995         goto save_png_done;
996
997     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
998                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
999                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1000
1001     png_write_info(png_ptr, info_ptr);
1002
1003     if (setjmp(png_jmpbuf(png_ptr)))
1004         goto save_png_done;
1005
1006     png_write_image(png_ptr, row_pointers);
1007
1008     if (setjmp(png_jmpbuf(png_ptr)))
1009         goto save_png_done;
1010
1011     png_write_end(png_ptr, NULL);
1012     retval = true;
1013
1014 save_png_done:
1015     png_destroy_write_struct(&png_ptr, &info_ptr);
1016     delete[] screenshot;
1017     delete[] row_pointers;
1018     if (fp)
1019         fclose(fp);
1020     if (!retval)
1021         unlink(ConvertFileName(file_name));
1022     return retval;
1023 }
1024
1025
1026