2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
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.
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.
15 See the GNU General Public License for more details.
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.
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
40 #define INT32 INT32_jpeg
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 static bool save_image(const char * fname);
52 static bool save_png(const char * fname);
55 #include "openal_wrapper.h"
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
64 extern float multiplier;
66 extern float realmultiplier;
68 extern bool cellophane;
70 //extern int terraindetail;
71 //extern int texdetail;
72 extern float terraindetail;
73 extern float texdetail;
76 extern int numplayers;
78 extern Person player[maxplayers];
79 extern bool stillloading;
81 /*extern*/ bool gameFocused;
83 extern float slomospeed;
84 extern float slomofreq;
94 #include "MacCompatibility.h"
99 #include "win-res/resource.h"
106 SDL_Rect **resolutions = NULL;
107 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
108 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
109 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
110 static SDL_Rect *hardcoded_resolutions[] = {
119 unsigned int resolutionDepths[8][2] = {0};
121 int closestResolution(int width, int height);
122 int resolutionID(int width, int height);
124 void ReportError (char * strError);
126 void DrawGL(Game & game);
128 void CreateGLWindow (void);
129 Boolean SetUp (Game & game);
130 void DoUpdate (Game & game);
136 // statics/globals (internal only) ------------------------------------------
138 typedef struct tagPOINT {
147 #pragma warning(push)
148 #pragma warning(disable: 4273)
151 #define GL_FUNC(ret,fn,params,call,rt) \
153 static ret (GLAPIENTRY *p##fn) params = NULL; \
154 ret GLAPIENTRY fn params { rt p##fn call; } \
163 static bool lookup_glsym(const char *funcname, void **func)
165 *func = SDL_GL_GetProcAddress(funcname);
168 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
174 static bool lookup_all_glsyms(void)
177 #define GL_FUNC(ret,fn,params,call,rt) \
178 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
184 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
191 void sdlGetCursorPos(POINT *pt)
193 SDL_GetMouseState(&(pt->x), &(pt->y));
195 #define GetCursorPos(x) sdlGetCursorPos(x)
196 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
197 #define ScreenToClient(x, pt)
198 #define ClientToScreen(x, pt)
202 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
207 static bool g_button, fullscreen = true;
218 kForegroundSleep = 10,
219 kBackgroundSleep = 10000
226 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
229 char gcstrMode [256] = "";
231 UInt32 gSleepTime = kForegroundSleep;
232 Boolean gDone = false, gfFrontProcess = true;
237 static int _argc = 0;
238 static char **_argv = NULL;
241 bool cmdline(const char *cmd)
243 for (int i = 1; i < _argc; i++)
245 char *arg = _argv[i];
248 if (strcasecmp(arg, cmd) == 0)
256 // --------------------------------------------------------------------------
258 void ReportError (char * strError)
260 #ifdef _MSC_VER // !!! FIXME. --ryan.
261 throw std::exception( strError);
264 /* char errMsgCStr [256];
267 sprintf (errMsgCStr, "%s", strError);
269 // out as debug string
270 CToPStr (strErr, errMsgCStr);
275 //-----------------------------------------------------------------------------------------------------------------------
279 void DrawGL (Game & game)
281 if ( stereomode == stereoNone ) {
282 game.DrawGLScene(stereoCenter);
284 game.DrawGLScene(stereoLeft);
285 game.DrawGLScene(stereoRight);
289 static inline int clamp_sdl_mouse_button(Uint8 button)
291 if (button == 2) // right mouse button is button 3 in SDL.
293 else if (button == 3)
296 if ((button >= 1) && (button <= 3))
301 static void sdlEventProc(const SDL_Event &e, Game &game)
308 case SDL_MOUSEMOTION:
309 game.deltah += e.motion.xrel;
310 game.deltav += e.motion.yrel;
314 if ((e.key.keysym.sym == SDLK_g) &&
315 (e.key.keysym.mod & KMOD_CTRL) &&
316 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
317 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
318 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
319 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
329 // --------------------------------------------------------------------------
331 static Point gMidPoint;
333 Boolean SetUp (Game & game)
339 randSeed = UpTime().lo;
349 DefaultSettings(game);
351 if (!SDL_WasInit(SDL_INIT_VIDEO))
352 if (SDL_Init(SDL_INIT_VIDEO) == -1)
354 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
357 if(!LoadSettings(game)) {
358 fprintf(stderr, "Failed to load config, creating default\n");
361 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
365 if (SDL_GL_LoadLibrary(NULL) == -1)
367 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
372 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
373 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
374 res = hardcoded_resolutions;
376 // reverse list (it was sorted biggest to smallest by SDL)...
378 for (count = 0; res[count]; count++)
380 if ((res[count]->w < 640) || (res[count]->h < 480))
381 break; // sane lower limit.
384 static SDL_Rect *resolutions_block = NULL;
385 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
386 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
387 if ((resolutions_block == NULL) || (resolutions == NULL))
390 fprintf(stderr, "Out of memory!\n");
394 resolutions[count--] = NULL;
395 for (int i = 0; count >= 0; i++, count--)
397 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
398 resolutions[count] = &resolutions_block[count];
401 if (cmdline("showresolutions"))
403 printf("Resolutions we think are okay:\n");
404 for (int i = 0; resolutions[i]; i++)
405 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
408 Uint32 sdlflags = SDL_OPENGL;
409 if (!cmdline("windowed"))
410 sdlflags |= SDL_FULLSCREEN;
412 SDL_WM_SetCaption("Lugaru", "Lugaru");
416 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
417 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
419 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
421 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
422 fprintf(stderr, "forcing 640x480...\n");
424 kContextHeight = 480;
425 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
427 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
428 fprintf(stderr, "forcing 640x480 windowed mode...\n");
429 sdlflags &= ~SDL_FULLSCREEN;
430 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
432 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
439 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
441 fprintf(stderr, "Failed to get double buffered GL context!\n");
446 if (!lookup_all_glsyms())
452 if (!cmdline("nomousegrab"))
453 SDL_WM_GrabInput(SDL_GRAB_ON);
456 glClear( GL_COLOR_BUFFER_BIT );
460 glDisable( GL_ALPHA_TEST);
461 glDisable( GL_BLEND);
462 glDisable( GL_DEPTH_TEST);
463 // glDisable( GL_DITHER);
465 glDisable( GL_LIGHTING);
466 glDisable( GL_LOGIC_OP);
467 glDisable( GL_TEXTURE_1D);
468 glDisable( GL_TEXTURE_2D);
469 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
470 glPixelTransferi( GL_RED_SCALE, 1);
471 glPixelTransferi( GL_RED_BIAS, 0);
472 glPixelTransferi( GL_GREEN_SCALE, 1);
473 glPixelTransferi( GL_GREEN_BIAS, 0);
474 glPixelTransferi( GL_BLUE_SCALE, 1);
475 glPixelTransferi( GL_BLUE_BIAS, 0);
476 glPixelTransferi( GL_ALPHA_SCALE, 1);
477 glPixelTransferi( GL_ALPHA_BIAS, 0);
479 // set initial rendering states
480 glShadeModel( GL_SMOOTH);
482 glDepthFunc( GL_LEQUAL);
483 glDepthMask( GL_TRUE);
484 // glDepthRange( FRONT_CLIP, BACK_CLIP);
485 glEnable( GL_DEPTH_TEST);
486 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
487 glCullFace( GL_FRONT);
488 glEnable( GL_CULL_FACE);
489 glEnable( GL_LIGHTING);
490 // glEnable( GL_LIGHT_MODEL_AMBIENT);
491 glEnable( GL_DITHER);
492 glEnable( GL_COLOR_MATERIAL);
493 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
494 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
495 glAlphaFunc( GL_GREATER, 0.5f);
497 GLint width = kContextWidth;
498 GLint height = kContextHeight;
499 gMidPoint.h = width / 2;
500 gMidPoint.v = height / 2;
504 game.newdetail=detail;
505 game.newscreenwidth=screenwidth;
506 game.newscreenheight=screenheight;
508 if ( CanInitStereo(stereomode) ) {
509 InitStereo(stereomode);
511 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
512 stereomode = stereoNone;
521 static void DoMouse(Game & game)
524 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
526 game.deltah *= usermousesensitivity;
527 game.deltav *= usermousesensitivity;
528 game.mousecoordh += game.deltah;
529 game.mousecoordv += game.deltav;
530 if (game.mousecoordh < 0)
531 game.mousecoordh = 0;
532 else if (game.mousecoordh >= kContextWidth)
533 game.mousecoordh = kContextWidth - 1;
534 if (game.mousecoordv < 0)
535 game.mousecoordv = 0;
536 else if (game.mousecoordv >= kContextHeight)
537 game.mousecoordv = kContextHeight - 1;
542 void DoFrameRate (int update)
544 static long frames = 0;
546 static AbsoluteTime time = {0,0};
547 static AbsoluteTime frametime = {0,0};
548 AbsoluteTime currTime = UpTime ();
549 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
551 if (0 > deltaTime) // if negative microseconds
552 deltaTime /= -1000000.0;
553 else // else milliseconds
556 multiplier=deltaTime;
557 if(multiplier<.001) multiplier=.001;
558 if(multiplier>10) multiplier=10;
559 if(update) frametime = currTime; // reset for next time interval
561 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
563 if (0 > deltaTime) // if negative microseconds
564 deltaTime /= -1000000.0;
565 else // else milliseconds
568 if (0.001 <= deltaTime) // has update interval passed
571 time = currTime; // reset for next time interval
578 void DoUpdate (Game & game)
580 static float sps=200;
582 static float oldmult;
585 if(multiplier>.6)multiplier=.6;
587 game.fps=1/multiplier;
589 count = multiplier*sps;
591 //if(count>10)count=10;
593 realmultiplier=multiplier;
594 multiplier*=gamespeed;
595 if(difficulty==1)multiplier*=.9;
596 if(difficulty==0)multiplier*=.8;
598 if(game.loading==4)multiplier*=.00001;
600 if(slomo&&!mainmenu)multiplier*=slomospeed;
601 //if(freeze)multiplier*=0.00001;
603 multiplier/=(float)count;
609 for(int i=0;i<count;i++)
615 game.TickOnceAfter();
616 /* - Debug code to test how many channels were active on average per frame
617 static long frames = 0;
619 static AbsoluteTime start = {0,0};
620 AbsoluteTime currTime = UpTime ();
621 static int num_channels = 0;
623 num_channels += OPENAL_GetChannelsPlaying();
624 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
626 if (0 > deltaTime) // if negative microseconds
627 deltaTime /= -1000000.0;
628 else // else milliseconds
636 float avg_channels = (float)num_channels / (float)frames;
638 ofstream opstream("log.txt",ios::app);
639 opstream << "Average frame count: ";
641 opstream << " frames - ";
642 opstream << avg_channels;
643 opstream << " per frame.\n";
653 // --------------------------------------------------------------------------
666 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
669 // cheat here...static destructors are calling glDeleteTexture() after
670 // the context is destroyed and libGL unloaded by SDL_Quit().
671 pglDeleteTextures = glDeleteTextures_doNothing;
675 // --------------------------------------------------------------------------
677 static bool IsFocused()
679 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
683 static void launch_web_browser(const char *url)
686 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
688 #elif (defined(__APPLE__) && defined(__MACH__))
689 const char *fmt = "open '%s'";
690 const size_t len = strlen(fmt) + strlen(url) + 16;
691 char *buf = new char[len];
692 snprintf(buf, len, fmt, url);
697 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
698 const size_t len = strlen(fmt) + strlen(url) + 16;
699 char *buf = new char[len];
700 snprintf(buf, len, fmt, url);
708 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
709 static char *findBinaryInPath(const char *bin, char *envr)
711 size_t alloc_size = 0;
719 ptr = strchr(start, ':'); /* find next $PATH separator. */
723 size = strlen(start) + strlen(bin) + 2;
724 if (size > alloc_size)
726 char *x = (char *) realloc(exe, size);
738 /* build full binary path... */
740 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
744 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
746 strcpy(exe, start); /* i'm lazy. piss off. */
750 start = ptr + 1; /* start points to beginning of next element. */
751 } while (ptr != NULL);
756 return(NULL); /* doesn't exist in path. */
757 } /* findBinaryInPath */
760 char *calcBaseDir(const char *argv0)
762 /* If there isn't a path on argv0, then look through the $PATH for it. */
766 const char *ptr = strrchr((char *)argv0, '/');
767 if (strchr(argv0, '/'))
769 retval = strdup(argv0);
771 *((char *) strrchr(retval, '/')) = '\0';
775 envr = getenv("PATH");
776 if (!envr) return NULL;
778 if (!envr) return NULL;
779 retval = findBinaryInPath(argv0, envr);
784 static inline void chdirToAppPath(const char *argv0)
786 char *dir = calcBaseDir(argv0);
789 #if (defined(__APPLE__) && defined(__MACH__))
790 // Chop off /Contents/MacOS if it's at the end of the string, so we
791 // land in the base of the app bundle.
792 const size_t len = strlen(dir);
793 const char *bundledirs = "/Contents/MacOS";
794 const size_t bundledirslen = strlen(bundledirs);
795 if (len > bundledirslen)
797 char *ptr = (dir + len) - bundledirslen;
798 if (strcasecmp(ptr, bundledirs) == 0)
809 int main(int argc, char **argv)
816 // !!! FIXME: we could use a Win32 API for this. --ryan.
818 chdirToAppPath(argv[0]);
823 //memset( &g_theKeys, 0, sizeof( KeyMap));
834 //ofstream os("error.txt");
836 //ofstream os("log.txt");
842 while (!gDone&&!game.quit&&(!game.tryquit))
848 // check windows messages
853 if(!game.isWaiting()) {
855 while( SDL_PollEvent( &e ) )
857 if( e.type == SDL_QUIT )
862 sdlEventProc(e, game);
873 // allow game chance to pause
878 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
880 SDL_WaitEvent((SDL_Event*)&evt);
881 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
883 else if (evt.type == SDL_QUIT)
888 regnow = game.registernow;
896 catch (const std::exception& error)
900 std::string e = "Caught exception: ";
905 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
915 // --------------------------------------------------------------------------
917 extern int channels[100];
918 extern OPENAL_SAMPLE * samp[100];
919 extern OPENAL_STREAM * strm[20];
921 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
923 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
924 if (currSample && currSample == samp[chan])
926 if (OPENAL_GetPaused(channels[chan]))
928 OPENAL_StopSound(channels[chan]);
929 channels[chan] = OPENAL_FREE;
931 else if (OPENAL_IsPlaying(channels[chan]))
933 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
934 if (loop_mode & OPENAL_LOOP_OFF)
936 channels[chan] = OPENAL_FREE;
942 channels[chan] = OPENAL_FREE;
945 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
946 if (channels[chan] < 0)
948 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
952 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
954 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
955 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
957 OPENAL_StopSound(channels[chan]);
958 OPENAL_Stream_Stop(sptr);
962 OPENAL_Stream_Stop(sptr);
963 channels[chan] = OPENAL_FREE;
966 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
967 if (channels[chan] < 0)
969 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
974 bool LoadImage(const char * fname, TGAImageRec & tex)
976 if ( tex.data == NULL )
979 return load_image(fname, tex);
982 void ScreenShot(const char * fname)
989 static bool load_image(const char *file_name, TGAImageRec &tex)
991 const char *ptr = strrchr((char *)file_name, '.');
994 if (strcasecmp(ptr+1, "png") == 0)
995 return load_png(file_name, tex);
996 else if (strcasecmp(ptr+1, "jpg") == 0)
997 return load_jpg(file_name, tex);
1000 STUBBED("Unsupported image type");
1005 struct my_error_mgr {
1006 struct jpeg_error_mgr pub; /* "public" fields */
1007 jmp_buf setjmp_buffer; /* for return to caller */
1009 typedef struct my_error_mgr * my_error_ptr;
1012 static void my_error_exit(j_common_ptr cinfo)
1014 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1015 longjmp(err->setjmp_buffer, 1);
1018 /* stolen from public domain example.c code in libjpg distribution. */
1019 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1021 struct jpeg_decompress_struct cinfo;
1022 struct my_error_mgr jerr;
1023 JSAMPROW buffer[1]; /* Output row buffer */
1024 int row_stride; /* physical row width in output buffer */
1025 FILE *infile = fopen(file_name, "rb");
1030 cinfo.err = jpeg_std_error(&jerr.pub);
1031 jerr.pub.error_exit = my_error_exit;
1032 if (setjmp(jerr.setjmp_buffer)) {
1033 jpeg_destroy_decompress(&cinfo);
1038 jpeg_create_decompress(&cinfo);
1039 jpeg_stdio_src(&cinfo, infile);
1040 (void) jpeg_read_header(&cinfo, TRUE);
1042 cinfo.out_color_space = JCS_RGB;
1043 cinfo.quantize_colors = 0;
1044 (void) jpeg_calc_output_dimensions(&cinfo);
1045 (void) jpeg_start_decompress(&cinfo);
1047 row_stride = cinfo.output_width * cinfo.output_components;
1048 tex.sizeX = cinfo.output_width;
1049 tex.sizeY = cinfo.output_height;
1052 while (cinfo.output_scanline < cinfo.output_height) {
1053 buffer[0] = (JSAMPROW)(char *)tex.data +
1054 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1055 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1058 (void) jpeg_finish_decompress(&cinfo);
1059 jpeg_destroy_decompress(&cinfo);
1066 /* stolen from public domain example.c code in libpng distribution. */
1067 static bool load_png(const char *file_name, TGAImageRec &tex)
1069 bool hasalpha = false;
1070 png_structp png_ptr = NULL;
1071 png_infop info_ptr = NULL;
1072 png_uint_32 width, height;
1073 int bit_depth, color_type, interlace_type;
1074 png_byte **rows = NULL;
1075 bool retval = false;
1076 png_byte **row_pointers = NULL;
1077 FILE *fp = fopen(file_name, "rb");
1082 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1083 if (png_ptr == NULL)
1086 info_ptr = png_create_info_struct(png_ptr);
1087 if (info_ptr == NULL)
1090 if (setjmp(png_jmpbuf(png_ptr)))
1093 png_init_io(png_ptr, fp);
1094 png_read_png(png_ptr, info_ptr,
1095 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1097 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1098 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1100 if (bit_depth != 8) // transform SHOULD handle this...
1103 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1106 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1109 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1110 row_pointers = png_get_rows(png_ptr, info_ptr);
1116 png_byte *dst = tex.data;
1117 for (int i = height-1; i >= 0; i--)
1119 png_byte *src = row_pointers[i];
1120 for (int j = 0; j < width; j++)
1134 png_byte *dst = tex.data;
1135 int pitch = width * 4;
1136 for (int i = height-1; i >= 0; i--, dst += pitch)
1137 memcpy(dst, row_pointers[i], pitch);
1146 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1153 static bool save_image(const char *file_name)
1155 const char *ptr = strrchr((char *)file_name, '.');
1158 if (strcasecmp(ptr+1, "png") == 0)
1159 return save_png(file_name);
1162 STUBBED("Unsupported image type");
1167 static bool save_png(const char *file_name)
1170 png_structp png_ptr = NULL;
1171 png_infop info_ptr = NULL;
1172 bool retval = false;
1174 fp = fopen(file_name, "wb");
1178 png_bytep *row_pointers = new png_bytep[kContextHeight];
1179 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1180 if ((!screenshot) || (!row_pointers))
1184 glReadPixels(0, 0, kContextWidth, kContextHeight,
1185 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1186 if (glGetError() != GL_NO_ERROR)
1189 for (int i = 0; i < kContextHeight; i++)
1190 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1192 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1193 if (png_ptr == NULL)
1196 info_ptr = png_create_info_struct(png_ptr);
1197 if (info_ptr == NULL)
1200 if (setjmp(png_jmpbuf(png_ptr)))
1203 png_init_io(png_ptr, fp);
1205 if (setjmp(png_jmpbuf(png_ptr)))
1208 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1209 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1210 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1212 png_write_info(png_ptr, info_ptr);
1214 if (setjmp(png_jmpbuf(png_ptr)))
1217 png_write_image(png_ptr, row_pointers);
1219 if (setjmp(png_jmpbuf(png_ptr)))
1222 png_write_end(png_ptr, NULL);
1226 png_destroy_write_struct(&png_ptr, &info_ptr);
1227 delete[] screenshot;
1228 delete[] row_pointers;
1232 unlink(ConvertFileName(file_name));