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);
290 /*static KeyMap g_theKeys;
292 void SetKey( int key)
294 g_theKeys[ key >> 3] |= (1 << (key & 7));
297 void ClearKey( int key)
299 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
302 void GetKeys( unsigned char theKeys[16])
304 memcpy( theKeys, &g_theKeys, 16);
309 return SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(SDL_BUTTON_LEFT);
312 static inline int clamp_sdl_mouse_button(Uint8 button)
314 if (button == 2) // right mouse button is button 3 in SDL.
316 else if (button == 3)
319 if ((button >= 1) && (button <= 3))
324 static void sdlEventProc(const SDL_Event &e, Game &game)
331 case SDL_MOUSEMOTION:
332 game.deltah += e.motion.xrel;
333 game.deltav += e.motion.yrel;
337 if ((e.key.keysym.sym == SDLK_g) &&
338 (e.key.keysym.mod & KMOD_CTRL) &&
339 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
340 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
341 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
342 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
352 // --------------------------------------------------------------------------
354 static Point gMidPoint;
356 Boolean SetUp (Game & game)
362 randSeed = UpTime().lo;
372 DefaultSettings(game);
374 if (!SDL_WasInit(SDL_INIT_VIDEO))
375 if (SDL_Init(SDL_INIT_VIDEO) == -1)
377 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
380 if(!LoadSettings(game)) {
381 fprintf(stderr, "Failed to load config, creating default\n");
384 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
388 if (SDL_GL_LoadLibrary(NULL) == -1)
390 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
395 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
396 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
397 res = hardcoded_resolutions;
399 // reverse list (it was sorted biggest to smallest by SDL)...
401 for (count = 0; res[count]; count++)
403 if ((res[count]->w < 640) || (res[count]->h < 480))
404 break; // sane lower limit.
407 static SDL_Rect *resolutions_block = NULL;
408 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
409 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
410 if ((resolutions_block == NULL) || (resolutions == NULL))
413 fprintf(stderr, "Out of memory!\n");
417 resolutions[count--] = NULL;
418 for (int i = 0; count >= 0; i++, count--)
420 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
421 resolutions[count] = &resolutions_block[count];
424 if (cmdline("showresolutions"))
426 printf("Resolutions we think are okay:\n");
427 for (int i = 0; resolutions[i]; i++)
428 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
431 Uint32 sdlflags = SDL_OPENGL;
432 if (!cmdline("windowed"))
433 sdlflags |= SDL_FULLSCREEN;
435 SDL_WM_SetCaption("Lugaru", "Lugaru");
439 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
440 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
442 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
444 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
445 fprintf(stderr, "forcing 640x480...\n");
447 kContextHeight = 480;
448 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
450 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
451 fprintf(stderr, "forcing 640x480 windowed mode...\n");
452 sdlflags &= ~SDL_FULLSCREEN;
453 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
455 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
462 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
464 fprintf(stderr, "Failed to get double buffered GL context!\n");
469 if (!lookup_all_glsyms())
475 if (!cmdline("nomousegrab"))
476 SDL_WM_GrabInput(SDL_GRAB_ON);
479 glClear( GL_COLOR_BUFFER_BIT );
483 glDisable( GL_ALPHA_TEST);
484 glDisable( GL_BLEND);
485 glDisable( GL_DEPTH_TEST);
486 // glDisable( GL_DITHER);
488 glDisable( GL_LIGHTING);
489 glDisable( GL_LOGIC_OP);
490 glDisable( GL_TEXTURE_1D);
491 glDisable( GL_TEXTURE_2D);
492 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
493 glPixelTransferi( GL_RED_SCALE, 1);
494 glPixelTransferi( GL_RED_BIAS, 0);
495 glPixelTransferi( GL_GREEN_SCALE, 1);
496 glPixelTransferi( GL_GREEN_BIAS, 0);
497 glPixelTransferi( GL_BLUE_SCALE, 1);
498 glPixelTransferi( GL_BLUE_BIAS, 0);
499 glPixelTransferi( GL_ALPHA_SCALE, 1);
500 glPixelTransferi( GL_ALPHA_BIAS, 0);
502 // set initial rendering states
503 glShadeModel( GL_SMOOTH);
505 glDepthFunc( GL_LEQUAL);
506 glDepthMask( GL_TRUE);
507 // glDepthRange( FRONT_CLIP, BACK_CLIP);
508 glEnable( GL_DEPTH_TEST);
509 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
510 glCullFace( GL_FRONT);
511 glEnable( GL_CULL_FACE);
512 glEnable( GL_LIGHTING);
513 // glEnable( GL_LIGHT_MODEL_AMBIENT);
514 glEnable( GL_DITHER);
515 glEnable( GL_COLOR_MATERIAL);
516 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
517 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
518 glAlphaFunc( GL_GREATER, 0.5f);
520 GLint width = kContextWidth;
521 GLint height = kContextHeight;
522 gMidPoint.h = width / 2;
523 gMidPoint.v = height / 2;
527 game.newdetail=detail;
528 game.newscreenwidth=screenwidth;
529 game.newscreenheight=screenheight;
531 if ( CanInitStereo(stereomode) ) {
532 InitStereo(stereomode);
534 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
535 stereomode = stereoNone;
544 static void DoMouse(Game & game)
547 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
549 game.deltah *= usermousesensitivity;
550 game.deltav *= usermousesensitivity;
551 game.mousecoordh += game.deltah;
552 game.mousecoordv += game.deltav;
553 if (game.mousecoordh < 0)
554 game.mousecoordh = 0;
555 else if (game.mousecoordh >= kContextWidth)
556 game.mousecoordh = kContextWidth - 1;
557 if (game.mousecoordv < 0)
558 game.mousecoordv = 0;
559 else if (game.mousecoordv >= kContextHeight)
560 game.mousecoordv = kContextHeight - 1;
565 void DoFrameRate (int update)
567 static long frames = 0;
569 static AbsoluteTime time = {0,0};
570 static AbsoluteTime frametime = {0,0};
571 AbsoluteTime currTime = UpTime ();
572 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
574 if (0 > deltaTime) // if negative microseconds
575 deltaTime /= -1000000.0;
576 else // else milliseconds
579 multiplier=deltaTime;
580 if(multiplier<.001) multiplier=.001;
581 if(multiplier>10) multiplier=10;
582 if(update) frametime = currTime; // reset for next time interval
584 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
586 if (0 > deltaTime) // if negative microseconds
587 deltaTime /= -1000000.0;
588 else // else milliseconds
591 if (0.001 <= deltaTime) // has update interval passed
594 time = currTime; // reset for next time interval
601 void DoUpdate (Game & game)
603 static float sps=200;
605 static float oldmult;
608 if(multiplier>.6)multiplier=.6;
610 game.fps=1/multiplier;
612 count = multiplier*sps;
614 //if(count>10)count=10;
616 realmultiplier=multiplier;
617 multiplier*=gamespeed;
618 if(difficulty==1)multiplier*=.9;
619 if(difficulty==0)multiplier*=.8;
621 if(game.loading==4)multiplier*=.00001;
623 if(slomo&&!mainmenu)multiplier*=slomospeed;
624 //if(freeze)multiplier*=0.00001;
626 multiplier/=(float)count;
632 for(int i=0;i<count;i++)
638 game.TickOnceAfter();
639 /* - Debug code to test how many channels were active on average per frame
640 static long frames = 0;
642 static AbsoluteTime start = {0,0};
643 AbsoluteTime currTime = UpTime ();
644 static int num_channels = 0;
646 num_channels += OPENAL_GetChannelsPlaying();
647 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
649 if (0 > deltaTime) // if negative microseconds
650 deltaTime /= -1000000.0;
651 else // else milliseconds
659 float avg_channels = (float)num_channels / (float)frames;
661 ofstream opstream("log.txt",ios::app);
662 opstream << "Average frame count: ";
664 opstream << " frames - ";
665 opstream << avg_channels;
666 opstream << " per frame.\n";
676 // --------------------------------------------------------------------------
689 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
692 // cheat here...static destructors are calling glDeleteTexture() after
693 // the context is destroyed and libGL unloaded by SDL_Quit().
694 pglDeleteTextures = glDeleteTextures_doNothing;
698 // --------------------------------------------------------------------------
700 static bool IsFocused()
702 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
706 static void launch_web_browser(const char *url)
709 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
711 #elif (defined(__APPLE__) && defined(__MACH__))
712 const char *fmt = "open '%s'";
713 const size_t len = strlen(fmt) + strlen(url) + 16;
714 char *buf = new char[len];
715 snprintf(buf, len, fmt, url);
720 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
721 const size_t len = strlen(fmt) + strlen(url) + 16;
722 char *buf = new char[len];
723 snprintf(buf, len, fmt, url);
731 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
732 static char *findBinaryInPath(const char *bin, char *envr)
734 size_t alloc_size = 0;
742 ptr = strchr(start, ':'); /* find next $PATH separator. */
746 size = strlen(start) + strlen(bin) + 2;
747 if (size > alloc_size)
749 char *x = (char *) realloc(exe, size);
761 /* build full binary path... */
763 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
767 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
769 strcpy(exe, start); /* i'm lazy. piss off. */
773 start = ptr + 1; /* start points to beginning of next element. */
774 } while (ptr != NULL);
779 return(NULL); /* doesn't exist in path. */
780 } /* findBinaryInPath */
783 char *calcBaseDir(const char *argv0)
785 /* If there isn't a path on argv0, then look through the $PATH for it. */
789 const char *ptr = strrchr((char *)argv0, '/');
790 if (strchr(argv0, '/'))
792 retval = strdup(argv0);
794 *((char *) strrchr(retval, '/')) = '\0';
798 envr = getenv("PATH");
799 if (!envr) return NULL;
801 if (!envr) return NULL;
802 retval = findBinaryInPath(argv0, envr);
807 static inline void chdirToAppPath(const char *argv0)
809 char *dir = calcBaseDir(argv0);
812 #if (defined(__APPLE__) && defined(__MACH__))
813 // Chop off /Contents/MacOS if it's at the end of the string, so we
814 // land in the base of the app bundle.
815 const size_t len = strlen(dir);
816 const char *bundledirs = "/Contents/MacOS";
817 const size_t bundledirslen = strlen(bundledirs);
818 if (len > bundledirslen)
820 char *ptr = (dir + len) - bundledirslen;
821 if (strcasecmp(ptr, bundledirs) == 0)
832 int main(int argc, char **argv)
839 // !!! FIXME: we could use a Win32 API for this. --ryan.
841 chdirToAppPath(argv[0]);
846 //memset( &g_theKeys, 0, sizeof( KeyMap));
857 //ofstream os("error.txt");
859 //ofstream os("log.txt");
865 while (!gDone&&!game.quit&&(!game.tryquit))
871 // check windows messages
876 if(!game.isWaiting()) {
878 while( SDL_PollEvent( &e ) )
880 if( e.type == SDL_QUIT )
885 sdlEventProc(e, game);
896 // allow game chance to pause
901 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
902 STUBBED("give up CPU but sniff the event queue");
906 regnow = game.registernow;
914 catch (const std::exception& error)
918 std::string e = "Caught exception: ";
923 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
933 // --------------------------------------------------------------------------
935 extern int channels[100];
936 extern OPENAL_SAMPLE * samp[100];
937 extern OPENAL_STREAM * strm[20];
939 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
941 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
942 if (currSample && currSample == samp[chan])
944 if (OPENAL_GetPaused(channels[chan]))
946 OPENAL_StopSound(channels[chan]);
947 channels[chan] = OPENAL_FREE;
949 else if (OPENAL_IsPlaying(channels[chan]))
951 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
952 if (loop_mode & OPENAL_LOOP_OFF)
954 channels[chan] = OPENAL_FREE;
960 channels[chan] = OPENAL_FREE;
963 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
964 if (channels[chan] < 0)
966 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
970 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
972 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
973 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
975 OPENAL_StopSound(channels[chan]);
976 OPENAL_Stream_Stop(sptr);
980 OPENAL_Stream_Stop(sptr);
981 channels[chan] = OPENAL_FREE;
984 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
985 if (channels[chan] < 0)
987 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
992 bool LoadImage(const char * fname, TGAImageRec & tex)
994 if ( tex.data == NULL )
997 return load_image(fname, tex);
1000 void ScreenShot(const char * fname)
1007 static bool load_image(const char *file_name, TGAImageRec &tex)
1009 const char *ptr = strrchr((char *)file_name, '.');
1012 if (strcasecmp(ptr+1, "png") == 0)
1013 return load_png(file_name, tex);
1014 else if (strcasecmp(ptr+1, "jpg") == 0)
1015 return load_jpg(file_name, tex);
1018 STUBBED("Unsupported image type");
1023 struct my_error_mgr {
1024 struct jpeg_error_mgr pub; /* "public" fields */
1025 jmp_buf setjmp_buffer; /* for return to caller */
1027 typedef struct my_error_mgr * my_error_ptr;
1030 static void my_error_exit(j_common_ptr cinfo)
1032 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1033 longjmp(err->setjmp_buffer, 1);
1036 /* stolen from public domain example.c code in libjpg distribution. */
1037 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1039 struct jpeg_decompress_struct cinfo;
1040 struct my_error_mgr jerr;
1041 JSAMPROW buffer[1]; /* Output row buffer */
1042 int row_stride; /* physical row width in output buffer */
1043 FILE *infile = fopen(file_name, "rb");
1048 cinfo.err = jpeg_std_error(&jerr.pub);
1049 jerr.pub.error_exit = my_error_exit;
1050 if (setjmp(jerr.setjmp_buffer)) {
1051 jpeg_destroy_decompress(&cinfo);
1056 jpeg_create_decompress(&cinfo);
1057 jpeg_stdio_src(&cinfo, infile);
1058 (void) jpeg_read_header(&cinfo, TRUE);
1060 cinfo.out_color_space = JCS_RGB;
1061 cinfo.quantize_colors = 0;
1062 (void) jpeg_calc_output_dimensions(&cinfo);
1063 (void) jpeg_start_decompress(&cinfo);
1065 row_stride = cinfo.output_width * cinfo.output_components;
1066 tex.sizeX = cinfo.output_width;
1067 tex.sizeY = cinfo.output_height;
1070 while (cinfo.output_scanline < cinfo.output_height) {
1071 buffer[0] = (JSAMPROW)(char *)tex.data +
1072 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1073 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1076 (void) jpeg_finish_decompress(&cinfo);
1077 jpeg_destroy_decompress(&cinfo);
1084 /* stolen from public domain example.c code in libpng distribution. */
1085 static bool load_png(const char *file_name, TGAImageRec &tex)
1087 bool hasalpha = false;
1088 png_structp png_ptr = NULL;
1089 png_infop info_ptr = NULL;
1090 png_uint_32 width, height;
1091 int bit_depth, color_type, interlace_type;
1092 png_byte **rows = NULL;
1093 bool retval = false;
1094 png_byte **row_pointers = NULL;
1095 FILE *fp = fopen(file_name, "rb");
1100 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1101 if (png_ptr == NULL)
1104 info_ptr = png_create_info_struct(png_ptr);
1105 if (info_ptr == NULL)
1108 if (setjmp(png_jmpbuf(png_ptr)))
1111 png_init_io(png_ptr, fp);
1112 png_read_png(png_ptr, info_ptr,
1113 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1115 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1116 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1118 if (bit_depth != 8) // transform SHOULD handle this...
1121 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1124 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1127 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1128 row_pointers = png_get_rows(png_ptr, info_ptr);
1134 png_byte *dst = tex.data;
1135 for (int i = height-1; i >= 0; i--)
1137 png_byte *src = row_pointers[i];
1138 for (int j = 0; j < width; j++)
1152 png_byte *dst = tex.data;
1153 int pitch = width * 4;
1154 for (int i = height-1; i >= 0; i--, dst += pitch)
1155 memcpy(dst, row_pointers[i], pitch);
1164 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1171 static bool save_image(const char *file_name)
1173 const char *ptr = strrchr((char *)file_name, '.');
1176 if (strcasecmp(ptr+1, "png") == 0)
1177 return save_png(file_name);
1180 STUBBED("Unsupported image type");
1185 static bool save_png(const char *file_name)
1188 png_structp png_ptr = NULL;
1189 png_infop info_ptr = NULL;
1190 bool retval = false;
1192 fp = fopen(file_name, "wb");
1196 png_bytep *row_pointers = new png_bytep[kContextHeight];
1197 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1198 if ((!screenshot) || (!row_pointers))
1202 glReadPixels(0, 0, kContextWidth, kContextHeight,
1203 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1204 if (glGetError() != GL_NO_ERROR)
1207 for (int i = 0; i < kContextHeight; i++)
1208 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1210 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1211 if (png_ptr == NULL)
1214 info_ptr = png_create_info_struct(png_ptr);
1215 if (info_ptr == NULL)
1218 if (setjmp(png_jmpbuf(png_ptr)))
1221 png_init_io(png_ptr, fp);
1223 if (setjmp(png_jmpbuf(png_ptr)))
1226 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1227 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1228 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1230 png_write_info(png_ptr, info_ptr);
1232 if (setjmp(png_jmpbuf(png_ptr)))
1235 png_write_image(png_ptr, row_pointers);
1237 if (setjmp(png_jmpbuf(png_ptr)))
1240 png_write_end(png_ptr, NULL);
1244 png_destroy_write_struct(&png_ptr, &info_ptr);
1245 delete[] screenshot;
1246 delete[] row_pointers;
1250 unlink(ConvertFileName(file_name));