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 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;
69 extern float terraindetail;
70 extern float texdetail;
73 extern int numplayers;
75 extern Person player[maxplayers];
76 extern bool stillloading;
78 /*extern*/ bool gameFocused;
80 extern float slomospeed;
81 extern float slomofreq;
91 #include "MacCompatibility.h"
96 #include "win-res/resource.h"
101 SDL_Rect **resolutions = NULL;
102 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
103 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
104 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
105 static SDL_Rect *hardcoded_resolutions[] = {
112 void DrawGL(Game & game);
114 Boolean SetUp (Game & game);
115 void DoUpdate (Game & game);
119 // statics/globals (internal only) ------------------------------------------
122 #pragma warning(push)
123 #pragma warning(disable: 4273)
126 #define GL_FUNC(ret,fn,params,call,rt) \
128 static ret (GLAPIENTRY *p##fn) params = NULL; \
129 ret GLAPIENTRY fn params { rt p##fn call; } \
138 static bool lookup_glsym(const char *funcname, void **func)
140 *func = SDL_GL_GetProcAddress(funcname);
143 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
149 static bool lookup_all_glsyms(void)
152 #define GL_FUNC(ret,fn,params,call,rt) \
153 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
159 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
167 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
174 Boolean gDone = false;
179 static int _argc = 0;
180 static char **_argv = NULL;
183 bool cmdline(const char *cmd)
185 for (int i = 1; i < _argc; i++)
187 char *arg = _argv[i];
190 if (strcasecmp(arg, cmd) == 0)
197 //-----------------------------------------------------------------------------------------------------------------------
201 static void sdlEventProc(const SDL_Event &e, Game &game)
205 case SDL_MOUSEMOTION:
206 game.deltah += e.motion.xrel;
207 game.deltav += e.motion.yrel;
211 if ((e.key.keysym.sym == SDLK_g) &&
212 (e.key.keysym.mod & KMOD_CTRL) &&
213 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
214 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
215 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
216 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
223 // --------------------------------------------------------------------------
225 static Point gMidPoint;
227 Boolean SetUp (Game & game)
233 randSeed = UpTime().lo;
243 DefaultSettings(game);
245 if (!SDL_WasInit(SDL_INIT_VIDEO))
246 if (SDL_Init(SDL_INIT_VIDEO) == -1)
248 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
251 if(!LoadSettings(game)) {
252 fprintf(stderr, "Failed to load config, creating default\n");
255 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
259 if (SDL_GL_LoadLibrary(NULL) == -1)
261 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
266 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
267 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
268 res = hardcoded_resolutions;
270 // reverse list (it was sorted biggest to smallest by SDL)...
272 for (count = 0; res[count]; count++)
274 if ((res[count]->w < 640) || (res[count]->h < 480))
275 break; // sane lower limit.
278 static SDL_Rect *resolutions_block = NULL;
279 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
280 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
281 if ((resolutions_block == NULL) || (resolutions == NULL))
284 fprintf(stderr, "Out of memory!\n");
288 resolutions[count--] = NULL;
289 for (int i = 0; count >= 0; i++, count--)
291 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
292 resolutions[count] = &resolutions_block[count];
295 if (cmdline("showresolutions"))
297 printf("Resolutions we think are okay:\n");
298 for (int i = 0; resolutions[i]; i++)
299 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
302 Uint32 sdlflags = SDL_OPENGL;
303 if (!cmdline("windowed"))
304 sdlflags |= SDL_FULLSCREEN;
306 SDL_WM_SetCaption("Lugaru", "Lugaru");
310 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
311 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
313 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
315 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
316 fprintf(stderr, "forcing 640x480...\n");
318 kContextHeight = 480;
319 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
321 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
322 fprintf(stderr, "forcing 640x480 windowed mode...\n");
323 sdlflags &= ~SDL_FULLSCREEN;
324 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
326 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
333 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
335 fprintf(stderr, "Failed to get double buffered GL context!\n");
340 if (!lookup_all_glsyms())
346 if (!cmdline("nomousegrab"))
347 SDL_WM_GrabInput(SDL_GRAB_ON);
350 glClear( GL_COLOR_BUFFER_BIT );
354 glDisable( GL_ALPHA_TEST);
355 glDisable( GL_BLEND);
356 glDisable( GL_DEPTH_TEST);
357 // glDisable( GL_DITHER);
359 glDisable( GL_LIGHTING);
360 glDisable( GL_LOGIC_OP);
361 glDisable( GL_TEXTURE_1D);
362 glDisable( GL_TEXTURE_2D);
363 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
364 glPixelTransferi( GL_RED_SCALE, 1);
365 glPixelTransferi( GL_RED_BIAS, 0);
366 glPixelTransferi( GL_GREEN_SCALE, 1);
367 glPixelTransferi( GL_GREEN_BIAS, 0);
368 glPixelTransferi( GL_BLUE_SCALE, 1);
369 glPixelTransferi( GL_BLUE_BIAS, 0);
370 glPixelTransferi( GL_ALPHA_SCALE, 1);
371 glPixelTransferi( GL_ALPHA_BIAS, 0);
373 // set initial rendering states
374 glShadeModel( GL_SMOOTH);
376 glDepthFunc( GL_LEQUAL);
377 glDepthMask( GL_TRUE);
378 // glDepthRange( FRONT_CLIP, BACK_CLIP);
379 glEnable( GL_DEPTH_TEST);
380 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
381 glCullFace( GL_FRONT);
382 glEnable( GL_CULL_FACE);
383 glEnable( GL_LIGHTING);
384 // glEnable( GL_LIGHT_MODEL_AMBIENT);
385 glEnable( GL_DITHER);
386 glEnable( GL_COLOR_MATERIAL);
387 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
388 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
389 glAlphaFunc( GL_GREATER, 0.5f);
391 GLint width = kContextWidth;
392 GLint height = kContextHeight;
393 gMidPoint.h = width / 2;
394 gMidPoint.v = height / 2;
398 game.newdetail=detail;
399 game.newscreenwidth=screenwidth;
400 game.newscreenheight=screenheight;
402 if ( CanInitStereo(stereomode) ) {
403 InitStereo(stereomode);
405 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
406 stereomode = stereoNone;
415 static void DoMouse(Game & game)
418 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
420 game.deltah *= usermousesensitivity;
421 game.deltav *= usermousesensitivity;
422 game.mousecoordh += game.deltah;
423 game.mousecoordv += game.deltav;
424 if (game.mousecoordh < 0)
425 game.mousecoordh = 0;
426 else if (game.mousecoordh >= kContextWidth)
427 game.mousecoordh = kContextWidth - 1;
428 if (game.mousecoordv < 0)
429 game.mousecoordv = 0;
430 else if (game.mousecoordv >= kContextHeight)
431 game.mousecoordv = kContextHeight - 1;
436 void DoFrameRate (int update)
438 static long frames = 0;
440 static AbsoluteTime time = {0,0};
441 static AbsoluteTime frametime = {0,0};
442 AbsoluteTime currTime = UpTime ();
443 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
445 if (0 > deltaTime) // if negative microseconds
446 deltaTime /= -1000000.0;
447 else // else milliseconds
450 multiplier=deltaTime;
451 if(multiplier<.001) multiplier=.001;
452 if(multiplier>10) multiplier=10;
453 if(update) frametime = currTime; // reset for next time interval
455 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
457 if (0 > deltaTime) // if negative microseconds
458 deltaTime /= -1000000.0;
459 else // else milliseconds
462 if (0.001 <= deltaTime) // has update interval passed
465 time = currTime; // reset for next time interval
472 void DoUpdate (Game & game)
474 static float sps=200;
476 static float oldmult;
479 if(multiplier>.6)multiplier=.6;
481 game.fps=1/multiplier;
483 count = multiplier*sps;
485 //if(count>10)count=10;
487 realmultiplier=multiplier;
488 multiplier*=gamespeed;
489 if(difficulty==1)multiplier*=.9;
490 if(difficulty==0)multiplier*=.8;
492 if(game.loading==4)multiplier*=.00001;
494 if(slomo&&!mainmenu)multiplier*=slomospeed;
495 //if(freeze)multiplier*=0.00001;
497 multiplier/=(float)count;
503 for(int i=0;i<count;i++)
509 game.TickOnceAfter();
510 /* - Debug code to test how many channels were active on average per frame
511 static long frames = 0;
513 static AbsoluteTime start = {0,0};
514 AbsoluteTime currTime = UpTime ();
515 static int num_channels = 0;
517 num_channels += OPENAL_GetChannelsPlaying();
518 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
520 if (0 > deltaTime) // if negative microseconds
521 deltaTime /= -1000000.0;
522 else // else milliseconds
530 float avg_channels = (float)num_channels / (float)frames;
532 ofstream opstream("log.txt",ios::app);
533 opstream << "Average frame count: ";
535 opstream << " frames - ";
536 opstream << avg_channels;
537 opstream << " per frame.\n";
547 // --------------------------------------------------------------------------
555 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
558 // cheat here...static destructors are calling glDeleteTexture() after
559 // the context is destroyed and libGL unloaded by SDL_Quit().
560 pglDeleteTextures = glDeleteTextures_doNothing;
564 // --------------------------------------------------------------------------
566 static bool IsFocused()
568 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
572 static void launch_web_browser(const char *url)
575 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
577 #elif (defined(__APPLE__) && defined(__MACH__))
578 const char *fmt = "open '%s'";
579 const size_t len = strlen(fmt) + strlen(url) + 16;
580 char *buf = new char[len];
581 snprintf(buf, len, fmt, url);
586 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
587 const size_t len = strlen(fmt) + strlen(url) + 16;
588 char *buf = new char[len];
589 snprintf(buf, len, fmt, url);
597 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
598 static char *findBinaryInPath(const char *bin, char *envr)
600 size_t alloc_size = 0;
608 ptr = strchr(start, ':'); /* find next $PATH separator. */
612 size = strlen(start) + strlen(bin) + 2;
613 if (size > alloc_size)
615 char *x = (char *) realloc(exe, size);
627 /* build full binary path... */
629 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
633 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
635 strcpy(exe, start); /* i'm lazy. piss off. */
639 start = ptr + 1; /* start points to beginning of next element. */
640 } while (ptr != NULL);
645 return(NULL); /* doesn't exist in path. */
646 } /* findBinaryInPath */
649 char *calcBaseDir(const char *argv0)
651 /* If there isn't a path on argv0, then look through the $PATH for it. */
655 const char *ptr = strrchr((char *)argv0, '/');
656 if (strchr(argv0, '/'))
658 retval = strdup(argv0);
660 *((char *) strrchr(retval, '/')) = '\0';
664 envr = getenv("PATH");
665 if (!envr) return NULL;
667 if (!envr) return NULL;
668 retval = findBinaryInPath(argv0, envr);
673 static inline void chdirToAppPath(const char *argv0)
675 char *dir = calcBaseDir(argv0);
678 #if (defined(__APPLE__) && defined(__MACH__))
679 // Chop off /Contents/MacOS if it's at the end of the string, so we
680 // land in the base of the app bundle.
681 const size_t len = strlen(dir);
682 const char *bundledirs = "/Contents/MacOS";
683 const size_t bundledirslen = strlen(bundledirs);
684 if (len > bundledirslen)
686 char *ptr = (dir + len) - bundledirslen;
687 if (strcasecmp(ptr, bundledirs) == 0)
698 int main(int argc, char **argv)
705 // !!! FIXME: we could use a Win32 API for this. --ryan.
707 chdirToAppPath(argv[0]);
719 //ofstream os("error.txt");
721 //ofstream os("log.txt");
727 while (!gDone&&!game.quit&&(!game.tryquit))
733 // check windows messages
738 if(!game.isWaiting()) {
740 while( SDL_PollEvent( &e ) )
742 if( e.type == SDL_QUIT )
747 sdlEventProc(e, game);
758 // allow game chance to pause
763 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
765 SDL_WaitEvent((SDL_Event*)&evt);
766 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
768 else if (evt.type == SDL_QUIT)
773 regnow = game.registernow;
781 catch (const std::exception& error)
785 std::string e = "Caught exception: ";
790 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
800 // --------------------------------------------------------------------------
802 extern int channels[100];
803 extern OPENAL_SAMPLE * samp[100];
804 extern OPENAL_STREAM * strm[20];
806 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
808 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
809 if (currSample && currSample == samp[chan])
811 if (OPENAL_GetPaused(channels[chan]))
813 OPENAL_StopSound(channels[chan]);
814 channels[chan] = OPENAL_FREE;
816 else if (OPENAL_IsPlaying(channels[chan]))
818 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
819 if (loop_mode & OPENAL_LOOP_OFF)
821 channels[chan] = OPENAL_FREE;
827 channels[chan] = OPENAL_FREE;
830 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
831 if (channels[chan] < 0)
833 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
837 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
839 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
840 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
842 OPENAL_StopSound(channels[chan]);
843 OPENAL_Stream_Stop(sptr);
847 OPENAL_Stream_Stop(sptr);
848 channels[chan] = OPENAL_FREE;
851 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
852 if (channels[chan] < 0)
854 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
859 bool LoadImage(const char * fname, TGAImageRec & tex)
861 if ( tex.data == NULL )
864 return load_image(fname, tex);
867 void ScreenShot(const char * fname)
874 static bool load_image(const char *file_name, TGAImageRec &tex)
876 const char *ptr = strrchr((char *)file_name, '.');
879 if (strcasecmp(ptr+1, "png") == 0)
880 return load_png(file_name, tex);
881 else if (strcasecmp(ptr+1, "jpg") == 0)
882 return load_jpg(file_name, tex);
885 STUBBED("Unsupported image type");
890 struct my_error_mgr {
891 struct jpeg_error_mgr pub; /* "public" fields */
892 jmp_buf setjmp_buffer; /* for return to caller */
894 typedef struct my_error_mgr * my_error_ptr;
897 static void my_error_exit(j_common_ptr cinfo)
899 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
900 longjmp(err->setjmp_buffer, 1);
903 /* stolen from public domain example.c code in libjpg distribution. */
904 static bool load_jpg(const char *file_name, TGAImageRec &tex)
906 struct jpeg_decompress_struct cinfo;
907 struct my_error_mgr jerr;
908 JSAMPROW buffer[1]; /* Output row buffer */
909 int row_stride; /* physical row width in output buffer */
910 FILE *infile = fopen(file_name, "rb");
915 cinfo.err = jpeg_std_error(&jerr.pub);
916 jerr.pub.error_exit = my_error_exit;
917 if (setjmp(jerr.setjmp_buffer)) {
918 jpeg_destroy_decompress(&cinfo);
923 jpeg_create_decompress(&cinfo);
924 jpeg_stdio_src(&cinfo, infile);
925 (void) jpeg_read_header(&cinfo, TRUE);
927 cinfo.out_color_space = JCS_RGB;
928 cinfo.quantize_colors = 0;
929 (void) jpeg_calc_output_dimensions(&cinfo);
930 (void) jpeg_start_decompress(&cinfo);
932 row_stride = cinfo.output_width * cinfo.output_components;
933 tex.sizeX = cinfo.output_width;
934 tex.sizeY = cinfo.output_height;
937 while (cinfo.output_scanline < cinfo.output_height) {
938 buffer[0] = (JSAMPROW)(char *)tex.data +
939 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
940 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
943 (void) jpeg_finish_decompress(&cinfo);
944 jpeg_destroy_decompress(&cinfo);
951 /* stolen from public domain example.c code in libpng distribution. */
952 static bool load_png(const char *file_name, TGAImageRec &tex)
954 bool hasalpha = false;
955 png_structp png_ptr = NULL;
956 png_infop info_ptr = NULL;
957 png_uint_32 width, height;
958 int bit_depth, color_type, interlace_type;
959 png_byte **rows = NULL;
961 png_byte **row_pointers = NULL;
962 FILE *fp = fopen(file_name, "rb");
967 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
971 info_ptr = png_create_info_struct(png_ptr);
972 if (info_ptr == NULL)
975 if (setjmp(png_jmpbuf(png_ptr)))
978 png_init_io(png_ptr, fp);
979 png_read_png(png_ptr, info_ptr,
980 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
982 png_get_IHDR(png_ptr, info_ptr, &width, &height,
983 &bit_depth, &color_type, &interlace_type, NULL, NULL);
985 if (bit_depth != 8) // transform SHOULD handle this...
988 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
991 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
994 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
995 row_pointers = png_get_rows(png_ptr, info_ptr);
1001 png_byte *dst = tex.data;
1002 for (int i = height-1; i >= 0; i--)
1004 png_byte *src = row_pointers[i];
1005 for (int j = 0; j < width; j++)
1019 png_byte *dst = tex.data;
1020 int pitch = width * 4;
1021 for (int i = height-1; i >= 0; i--, dst += pitch)
1022 memcpy(dst, row_pointers[i], pitch);
1031 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1038 bool save_image(const char *file_name)
1040 const char *ptr = strrchr((char *)file_name, '.');
1043 if (strcasecmp(ptr+1, "png") == 0)
1044 return save_png(file_name);
1047 STUBBED("Unsupported image type");
1052 static bool save_png(const char *file_name)
1055 png_structp png_ptr = NULL;
1056 png_infop info_ptr = NULL;
1057 bool retval = false;
1059 fp = fopen(file_name, "wb");
1063 png_bytep *row_pointers = new png_bytep[kContextHeight];
1064 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1065 if ((!screenshot) || (!row_pointers))
1069 glReadPixels(0, 0, kContextWidth, kContextHeight,
1070 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1071 if (glGetError() != GL_NO_ERROR)
1074 for (int i = 0; i < kContextHeight; i++)
1075 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1077 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1078 if (png_ptr == NULL)
1081 info_ptr = png_create_info_struct(png_ptr);
1082 if (info_ptr == NULL)
1085 if (setjmp(png_jmpbuf(png_ptr)))
1088 png_init_io(png_ptr, fp);
1090 if (setjmp(png_jmpbuf(png_ptr)))
1093 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1094 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1095 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1097 png_write_info(png_ptr, info_ptr);
1099 if (setjmp(png_jmpbuf(png_ptr)))
1102 png_write_image(png_ptr, row_pointers);
1104 if (setjmp(png_jmpbuf(png_ptr)))
1107 png_write_end(png_ptr, NULL);
1111 png_destroy_write_struct(&png_ptr, &info_ptr);
1112 delete[] screenshot;
1113 delete[] row_pointers;
1117 unlink(ConvertFileName(file_name));