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