]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
License: Update GPLv2+ header to match current FSF recommendation
[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 modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 Lugaru 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.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Lugaru.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 #ifdef WIN32
22 #include <windows.h>
23 #endif
24
25 #include "Game.h"
26
27 #include <jpeglib.h>
28 #include <png.h>
29 #include <zlib.h>
30
31 using namespace Game;
32
33 static bool load_image(const char * fname, TGAImageRec & tex);
34 static bool load_png(const char * fname, TGAImageRec & tex);
35 static bool load_jpg(const char * fname, TGAImageRec & tex);
36 bool save_image(const char * fname);
37 static bool save_png(const char * fname);
38
39
40 #include "openal_wrapper.h"
41
42 extern float multiplier;
43 extern float sps;
44 extern float realmultiplier;
45 extern int slomo;
46 extern bool cellophane;
47 extern float texdetail;
48
49 extern bool osx;
50 extern bool freeze;
51 extern bool stillloading;
52 extern int mainmenu;
53 /*extern*/
54 bool gameFocused;
55
56 extern float slomospeed;
57 extern float slomofreq;
58
59
60
61 #include <math.h>
62 #include <stdio.h>
63 #include <string.h>
64 #include <fstream>
65 #include <iostream>
66 #include <set>
67 #include "gamegl.h"
68 #include "MacCompatibility.h"
69 #include "Settings.h"
70
71 #ifdef WIN32
72 #include <shellapi.h>
73 #include "win-res/resource.h"
74 #endif
75
76 extern SDL_Window *sdlwindow;
77
78 using namespace std;
79
80 set<pair<int,int>> resolutions;
81
82 Boolean SetUp ();
83 void DoUpdate ();
84
85 void CleanUp (void);
86
87 // statics/globals (internal only) ------------------------------------------
88
89 #ifdef _MSC_VER
90 #pragma warning(push)
91 #pragma warning(disable: 4273)
92 #endif
93
94 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
95 #define GL_FUNC(ret,fn,params,call,rt) \
96     extern "C" { \
97         static ret (GLAPIENTRY *p##fn) params = NULL; \
98         ret GLAPIENTRY fn params { rt p##fn call; } \
99     }
100 #include "glstubs.h"
101 #undef GL_FUNC
102 #endif // __MINGW32__
103
104 #ifdef _MSC_VER
105 #pragma warning(pop)
106 #endif
107
108 static bool lookup_glsym(const char *funcname, void **func)
109 {
110     *func = SDL_GL_GetProcAddress(funcname);
111     if (*func == NULL) {
112         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
113         return false;
114     }
115     return true;
116 }
117
118 static bool lookup_all_glsyms(void)
119 {
120     bool retval = true;
121 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
122 #define GL_FUNC(ret,fn,params,call,rt) \
123         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
124 #include "glstubs.h"
125 #undef GL_FUNC
126 #endif // __MINGW32__
127     return retval;
128 }
129
130 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
131 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
132 {
133     // no-op.
134 }
135 #endif // __MINGW32__
136
137 #ifdef MessageBox
138 #undef MessageBox
139 #endif
140 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
141
142 // Menu defs
143
144 int kContextWidth;
145 int kContextHeight;
146
147 Boolean gDone = false;
148
149 static int _argc = 0;
150 static char **_argv = NULL;
151
152 bool cmdline(const char *cmd)
153 {
154     for (int i = 1; i < _argc; i++) {
155         char *arg = _argv[i];
156         while (*arg == '-')
157             arg++;
158         if (strcasecmp(arg, cmd) == 0)
159             return true;
160     }
161
162     return false;
163 }
164
165 //-----------------------------------------------------------------------------------------------------------------------
166
167 // OpenGL Drawing
168
169 void initGL()
170 {
171     glClear( GL_COLOR_BUFFER_BIT );
172     swap_gl_buffers();
173
174     // clear all states
175     glDisable( GL_ALPHA_TEST);
176     glDisable( GL_BLEND);
177     glDisable( GL_DEPTH_TEST);
178     //glDisable( GL_DITHER);
179     glDisable( GL_FOG);
180     glDisable( GL_LIGHTING);
181     glDisable( GL_LOGIC_OP);
182     glDisable( GL_TEXTURE_1D);
183     glDisable( GL_TEXTURE_2D);
184     glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
185     glPixelTransferi( GL_RED_SCALE, 1);
186     glPixelTransferi( GL_RED_BIAS, 0);
187     glPixelTransferi( GL_GREEN_SCALE, 1);
188     glPixelTransferi( GL_GREEN_BIAS, 0);
189     glPixelTransferi( GL_BLUE_SCALE, 1);
190     glPixelTransferi( GL_BLUE_BIAS, 0);
191     glPixelTransferi( GL_ALPHA_SCALE, 1);
192     glPixelTransferi( GL_ALPHA_BIAS, 0);
193
194     // set initial rendering states
195     glShadeModel( GL_SMOOTH);
196     glClearDepth( 1.0f);
197     glDepthFunc( GL_LEQUAL);
198     glDepthMask( GL_TRUE);
199     //glDepthRange( FRONT_CLIP, BACK_CLIP);
200     glEnable( GL_DEPTH_TEST);
201     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
202     glCullFace( GL_FRONT);
203     glEnable( GL_CULL_FACE);
204     glEnable( GL_LIGHTING);
205     //glEnable( GL_LIGHT_MODEL_AMBIENT);
206     glEnable( GL_DITHER);
207     glEnable( GL_COLOR_MATERIAL);
208     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
209     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
210     glAlphaFunc( GL_GREATER, 0.5f);
211
212     if ( CanInitStereo(stereomode) ) {
213         InitStereo(stereomode);
214     } else {
215         fprintf(stderr, "Failed to initialize stereo, disabling.\n");
216         stereomode = stereoNone;
217     }
218 }
219
220 void toggleFullscreen()
221 {
222     fullscreen = !fullscreen;
223     Uint32 flags = SDL_GetWindowFlags(sdlwindow);
224     if (flags & SDL_WINDOW_FULLSCREEN) {
225         flags &= ~SDL_WINDOW_FULLSCREEN;
226     } else {
227         flags |= SDL_WINDOW_FULLSCREEN;
228     }
229     SDL_SetWindowFullscreen(sdlwindow, flags);
230 }
231
232 static SDL_bool sdlEventProc(const SDL_Event &e)
233 {
234     switch (e.type) {
235         case SDL_QUIT:
236             return SDL_FALSE;
237
238         case SDL_WINDOWEVENT:
239             if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
240                 return SDL_FALSE;
241             }
242         break;
243
244         case SDL_MOUSEMOTION:
245             deltah += e.motion.xrel;
246             deltav += e.motion.yrel;
247         break;
248
249         case SDL_KEYDOWN:
250             if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
251                 (e.key.keysym.mod & KMOD_CTRL)) {
252                 SDL_bool mode = SDL_TRUE;
253                 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
254                     mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
255                 SDL_SetWindowGrab(sdlwindow, mode);
256                 SDL_SetRelativeMouseMode(mode);
257             } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
258                 toggleFullscreen();
259             }
260         break;
261     }
262     return SDL_TRUE;
263 }
264
265
266
267 // --------------------------------------------------------------------------
268
269 static Point gMidPoint;
270
271 Boolean SetUp ()
272 {
273     LOGFUNC;
274
275     osx = 0;
276     cellophane = 0;
277     texdetail = 4;
278     slomospeed = 0.25;
279     slomofreq = 8012;
280
281     DefaultSettings();
282
283     if (!SDL_WasInit(SDL_INIT_VIDEO))
284         if (SDL_Init(SDL_INIT_VIDEO) == -1) {
285             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
286             return false;
287         }
288     if (!LoadSettings()) {
289         fprintf(stderr, "Failed to load config, creating default\n");
290         SaveSettings();
291     }
292     if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
293         kBitsPerPixel = 16;
294     }
295
296     if (SDL_GL_LoadLibrary(NULL) == -1) {
297         fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
298         SDL_Quit();
299         return false;
300     }
301
302     for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
303         for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
304             SDL_DisplayMode mode;
305             if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
306                 continue;
307             if ((mode.w < 640) || (mode.h < 480))
308                 continue;  // sane lower limit.
309             pair<int,int> resolution(mode.w, mode.h);
310             resolutions.insert(resolution);
311         }
312     }
313
314     if (resolutions.empty()) {
315         const std::string error = "No suitable video resolutions found.";
316         cerr << error << endl;
317         SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
318         SDL_Quit();
319         return false;
320     }
321
322     if (cmdline("showresolutions")) {
323         printf("Available resolutions:\n");
324         for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
325             printf("  %d x %d\n", (int) resolution->first, (int) resolution->second);
326         }
327     }
328
329     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
330     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
331
332     Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
333     if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
334         fullscreen = 1;
335         sdlflags |= SDL_WINDOW_FULLSCREEN;
336     }
337     if (!cmdline("nomousegrab"))
338         sdlflags |= SDL_WINDOW_INPUT_GRABBED;
339
340     sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
341                                  kContextWidth, kContextHeight, sdlflags);
342
343     if (!sdlwindow) {
344         fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
345         fprintf(stderr, "forcing 640x480...\n");
346         kContextWidth = 640;
347         kContextHeight = 480;
348         sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
349                                      kContextWidth, kContextHeight, sdlflags);
350         if (!sdlwindow) {
351             fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
352             fprintf(stderr, "forcing 640x480 windowed mode...\n");
353             sdlflags &= ~SDL_WINDOW_FULLSCREEN;
354             sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
355                                          kContextWidth, kContextHeight, sdlflags);
356
357             if (!sdlwindow) {
358                 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
359                 return false;
360             }
361         }
362     }
363
364     SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
365     if (!glctx) {
366         fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
367         SDL_Quit();
368         return false;
369     }
370
371     SDL_GL_MakeCurrent(sdlwindow, glctx);
372
373     if (!lookup_all_glsyms()) {
374         fprintf(stderr, "Missing required OpenGL functions.\n");
375         SDL_Quit();
376         return false;
377     }
378
379     int dblbuf = 0;
380     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
381     {
382         fprintf(stderr, "Failed to get a double-buffered context.\n");
383         SDL_Quit();
384         return false;
385     }
386
387     if (SDL_GL_SetSwapInterval(-1) == -1)  // try swap_tear first.
388         SDL_GL_SetSwapInterval(1);
389
390     SDL_ShowCursor(0);
391     if (!cmdline("nomousegrab"))
392         SDL_SetRelativeMouseMode(SDL_TRUE);
393
394     initGL();
395
396     GLint width = kContextWidth;
397     GLint height = kContextHeight;
398     gMidPoint.h = width / 2;
399     gMidPoint.v = height / 2;
400     screenwidth = width;
401     screenheight = height;
402
403     newdetail = detail;
404     newscreenwidth = screenwidth;
405     newscreenheight = screenheight;
406
407     /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
408     pair<int,int> startresolution(width,height);
409     if (resolutions.find(startresolution) == resolutions.end()) {
410         resolutions.insert(startresolution);
411     }
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 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
568 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
569 #include "glstubs.h"
570 #undef GL_FUNC
571     // cheat here...static destructors are calling glDeleteTexture() after
572     //  the context is destroyed and libGL unloaded by SDL_Quit().
573     pglDeleteTextures = glDeleteTextures_doNothing;
574 #endif // __MINGW32__
575
576 }
577
578 // --------------------------------------------------------------------------
579
580 static bool IsFocused()
581 {
582     return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
583 }
584
585
586
587 #ifndef WIN32
588 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
589 static char *findBinaryInPath(const char *bin, char *envr)
590 {
591     size_t alloc_size = 0;
592     char *exe = NULL;
593     char *start = envr;
594     char *ptr;
595
596     do {
597         size_t size;
598         ptr = strchr(start, ':');  /* find next $PATH separator. */
599         if (ptr)
600             *ptr = '\0';
601
602         size = strlen(start) + strlen(bin) + 2;
603         if (size > alloc_size) {
604             char *x = (char *) realloc(exe, size);
605             if (x == NULL) {
606                 if (exe != NULL)
607                     free(exe);
608                 return(NULL);
609             } /* if */
610
611             alloc_size = size;
612             exe = x;
613         } /* if */
614
615         /* build full binary path... */
616         strcpy(exe, start);
617         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
618             strcat(exe, "/");
619         strcat(exe, bin);
620
621         if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
622             strcpy(exe, start);  /* i'm lazy. piss off. */
623             return(exe);
624         } /* if */
625
626         start = ptr + 1;  /* start points to beginning of next element. */
627     } while (ptr != NULL);
628
629     if (exe != NULL)
630         free(exe);
631
632     return(NULL);  /* doesn't exist in path. */
633 } /* findBinaryInPath */
634
635
636 char *calcBaseDir(const char *argv0)
637 {
638     /* If there isn't a path on argv0, then look through the $PATH for it. */
639     char *retval;
640     char *envr;
641
642     if (strchr(argv0, '/')) {
643         retval = strdup(argv0);
644         if (retval)
645             *((char *) strrchr(retval, '/')) = '\0';
646         return(retval);
647     }
648
649     envr = getenv("PATH");
650     if (!envr)
651         return NULL;
652     envr = strdup(envr);
653     if (!envr)
654         return NULL;
655     retval = findBinaryInPath(argv0, envr);
656     free(envr);
657     return(retval);
658 }
659
660 static inline void chdirToAppPath(const char *argv0)
661 {
662     char *dir = calcBaseDir(argv0);
663     if (dir) {
664 #if (defined(__APPLE__) && defined(__MACH__))
665         // Chop off /Contents/MacOS if it's at the end of the string, so we
666         //  land in the base of the app bundle.
667         const size_t len = strlen(dir);
668         const char *bundledirs = "/Contents/MacOS";
669         const size_t bundledirslen = strlen(bundledirs);
670         if (len > bundledirslen) {
671             char *ptr = (dir + len) - bundledirslen;
672             if (strcasecmp(ptr, bundledirs) == 0)
673                 *ptr = '\0';
674         }
675 #endif
676         chdir(dir);
677         free(dir);
678     }
679 }
680 #endif
681
682
683 int main(int argc, char **argv)
684 {
685     _argc = argc;
686     _argv = argv;
687
688     // !!! FIXME: we could use a Win32 API for this.  --ryan.
689 #ifndef WIN32
690     chdirToAppPath(argv[0]);
691 #endif
692
693     LOGFUNC;
694
695     try {
696         {
697             newGame();
698
699             //ofstream os("error.txt");
700             //os.close();
701             //ofstream os("log.txt");
702             //os.close();
703
704             if (!SetUp ())
705                 return 42;
706
707             while (!gDone && !tryquit) {
708                 if (IsFocused()) {
709                     gameFocused = true;
710
711                     // check windows messages
712
713                     deltah = 0;
714                     deltav = 0;
715                     SDL_Event e;
716                     if (!waiting) {
717                         // message pump
718                         while ( SDL_PollEvent( &e ) ) {
719                             if (!sdlEventProc(e)) {
720                                 gDone = true;
721                                 break;
722                             }
723                         }
724                     }
725
726                     // game
727                     DoUpdate();
728                 } else {
729                     if (gameFocused) {
730                         // allow game chance to pause
731                         gameFocused = false;
732                         DoUpdate();
733                     }
734
735                     // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
736                     SDL_WaitEvent(0);
737                 }
738             }
739
740             deleteGame();
741         }
742
743         CleanUp ();
744
745         return 0;
746     } catch (const std::exception& error) {
747         CleanUp();
748
749         std::string e = "Caught exception: ";
750         e += error.what();
751
752         LOG(e);
753
754         MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
755     }
756
757     CleanUp();
758
759     return -1;
760 }
761
762
763
764 // --------------------------------------------------------------------------
765
766
767 bool LoadImage(const char * fname, TGAImageRec & tex)
768 {
769     if ( tex.data == NULL )
770         return false;
771     else
772         return load_image(fname, tex);
773 }
774
775 void ScreenShot(const char * fname)
776 {
777
778 }
779
780
781
782 static bool load_image(const char *file_name, TGAImageRec &tex)
783 {
784     const char *ptr = strrchr((char *)file_name, '.');
785     if (ptr) {
786         if (strcasecmp(ptr + 1, "png") == 0)
787             return load_png(file_name, tex);
788         else if (strcasecmp(ptr + 1, "jpg") == 0)
789             return load_jpg(file_name, tex);
790     }
791
792     STUBBED("Unsupported image type");
793     return false;
794 }
795
796
797 struct my_error_mgr {
798     struct jpeg_error_mgr pub; /* "public" fields */
799     jmp_buf setjmp_buffer; /* for return to caller */
800 };
801 typedef struct my_error_mgr * my_error_ptr;
802
803
804 static void my_error_exit(j_common_ptr cinfo)
805 {
806     struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
807     longjmp(err->setjmp_buffer, 1);
808 }
809
810 /* stolen from public domain example.c code in libjpg distribution. */
811 static bool load_jpg(const char *file_name, TGAImageRec &tex)
812 {
813     struct jpeg_decompress_struct cinfo;
814     struct my_error_mgr jerr;
815     JSAMPROW buffer[1]; /* Output row buffer */
816     int row_stride; /* physical row width in output buffer */
817     FILE *infile = fopen(file_name, "rb");
818
819     if (infile == NULL)
820         return false;
821
822     cinfo.err = jpeg_std_error(&jerr.pub);
823     jerr.pub.error_exit = my_error_exit;
824     if (setjmp(jerr.setjmp_buffer)) {
825         jpeg_destroy_decompress(&cinfo);
826         fclose(infile);
827         return false;
828     }
829
830     jpeg_create_decompress(&cinfo);
831     jpeg_stdio_src(&cinfo, infile);
832     (void) jpeg_read_header(&cinfo, TRUE);
833
834     cinfo.out_color_space = JCS_RGB;
835     cinfo.quantize_colors = 0;
836     (void) jpeg_calc_output_dimensions(&cinfo);
837     (void) jpeg_start_decompress(&cinfo);
838
839     row_stride = cinfo.output_width * cinfo.output_components;
840     tex.sizeX = cinfo.output_width;
841     tex.sizeY = cinfo.output_height;
842     tex.bpp = 24;
843
844     while (cinfo.output_scanline < cinfo.output_height) {
845         buffer[0] = (JSAMPROW)(char *)tex.data +
846                     ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
847         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
848     }
849
850     (void) jpeg_finish_decompress(&cinfo);
851     jpeg_destroy_decompress(&cinfo);
852     fclose(infile);
853
854     return true;
855 }
856
857
858 /* stolen from public domain example.c code in libpng distribution. */
859 static bool load_png(const char *file_name, TGAImageRec &tex)
860 {
861     bool hasalpha = false;
862     png_structp png_ptr = NULL;
863     png_infop info_ptr = NULL;
864     png_uint_32 width, height;
865     int bit_depth, color_type, interlace_type;
866     bool retval = false;
867     png_byte **row_pointers = NULL;
868     FILE *fp = fopen(file_name, "rb");
869
870     if (fp == NULL) {
871         cerr << file_name << " not found" << endl;
872         return(NULL);
873     }
874
875     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
876     if (png_ptr == NULL)
877         goto png_done;
878
879     info_ptr = png_create_info_struct(png_ptr);
880     if (info_ptr == NULL)
881         goto png_done;
882
883     if (setjmp(png_jmpbuf(png_ptr)))
884         goto png_done;
885
886     png_init_io(png_ptr, fp);
887     png_read_png(png_ptr, info_ptr,
888                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
889                  NULL);
890     png_get_IHDR(png_ptr, info_ptr, &width, &height,
891                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
892
893     if (bit_depth != 8)  // transform SHOULD handle this...
894         goto png_done;
895
896     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
897         goto png_done;
898
899     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
900         goto png_done;
901
902     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
903     row_pointers = png_get_rows(png_ptr, info_ptr);
904     if (!row_pointers)
905         goto png_done;
906
907     if (!hasalpha) {
908         png_byte *dst = tex.data;
909         for (int i = height - 1; i >= 0; i--) {
910             png_byte *src = row_pointers[i];
911             for (unsigned j = 0; j < width; j++) {
912                 dst[0] = src[0];
913                 dst[1] = src[1];
914                 dst[2] = src[2];
915                 dst[3] = 0xFF;
916                 src += 3;
917                 dst += 4;
918             }
919         }
920     }
921
922     else {
923         png_byte *dst = tex.data;
924         int pitch = width * 4;
925         for (int i = height - 1; i >= 0; i--, dst += pitch)
926             memcpy(dst, row_pointers[i], pitch);
927     }
928
929     tex.sizeX = width;
930     tex.sizeY = height;
931     tex.bpp = 32;
932     retval = true;
933
934 png_done:
935     if (!retval) {
936         cerr << "There was a problem loading " << file_name << endl;
937     }
938     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
939     if (fp)
940         fclose(fp);
941     return (retval);
942 }
943
944
945 bool save_image(const char *file_name)
946 {
947     const char *ptr = strrchr((char *)file_name, '.');
948     if (ptr) {
949         if (strcasecmp(ptr + 1, "png") == 0)
950             return save_png(file_name);
951     }
952
953     STUBBED("Unsupported image type");
954     return false;
955 }
956
957
958 static bool save_png(const char *file_name)
959 {
960     FILE *fp = NULL;
961     png_structp png_ptr = NULL;
962     png_infop info_ptr = NULL;
963     bool retval = false;
964
965     fp = fopen(file_name, "wb");
966     if (fp == NULL)
967         return false;
968
969     png_bytep *row_pointers = new png_bytep[kContextHeight];
970     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
971     if ((!screenshot) || (!row_pointers))
972         goto save_png_done;
973
974     glGetError();
975     glReadPixels(0, 0, kContextWidth, kContextHeight,
976                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
977     if (glGetError() != GL_NO_ERROR)
978         goto save_png_done;
979
980     for (int i = 0; i < kContextHeight; i++)
981         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
982
983     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
984     if (png_ptr == NULL)
985         goto save_png_done;
986
987     info_ptr = png_create_info_struct(png_ptr);
988     if (info_ptr == NULL)
989         goto save_png_done;
990
991     if (setjmp(png_jmpbuf(png_ptr)))
992         goto save_png_done;
993
994     png_init_io(png_ptr, fp);
995
996     if (setjmp(png_jmpbuf(png_ptr)))
997         goto save_png_done;
998
999     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1000                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1001                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1002
1003     png_write_info(png_ptr, info_ptr);
1004
1005     if (setjmp(png_jmpbuf(png_ptr)))
1006         goto save_png_done;
1007
1008     png_write_image(png_ptr, row_pointers);
1009
1010     if (setjmp(png_jmpbuf(png_ptr)))
1011         goto save_png_done;
1012
1013     png_write_end(png_ptr, NULL);
1014     retval = true;
1015
1016 save_png_done:
1017     png_destroy_write_struct(&png_ptr, &info_ptr);
1018     delete[] screenshot;
1019     delete[] row_pointers;
1020     if (fp)
1021         fclose(fp);
1022     if (!retval)
1023         unlink(ConvertFileName(file_name));
1024     return retval;
1025 }
1026
1027
1028