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"
57 extern float multiplier;
59 extern float realmultiplier;
61 extern bool cellophane;
62 extern float texdetail;
66 extern bool stillloading;
68 /*extern*/ bool gameFocused;
70 extern float slomospeed;
71 extern float slomofreq;
81 #include "MacCompatibility.h"
86 #include "win-res/resource.h"
91 SDL_Rect **resolutions = NULL;
92 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
93 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
94 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
95 static SDL_Rect *hardcoded_resolutions[] = {
102 void DrawGL(Game & game);
104 Boolean SetUp (Game & game);
105 void DoUpdate (Game & game);
109 // statics/globals (internal only) ------------------------------------------
112 #pragma warning(push)
113 #pragma warning(disable: 4273)
116 #define GL_FUNC(ret,fn,params,call,rt) \
118 static ret (GLAPIENTRY *p##fn) params = NULL; \
119 ret GLAPIENTRY fn params { rt p##fn call; } \
128 static bool lookup_glsym(const char *funcname, void **func)
130 *func = SDL_GL_GetProcAddress(funcname);
133 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
139 static bool lookup_all_glsyms(void)
142 #define GL_FUNC(ret,fn,params,call,rt) \
143 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
149 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
157 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
164 Boolean gDone = false;
169 static int _argc = 0;
170 static char **_argv = NULL;
173 bool cmdline(const char *cmd)
175 for (int i = 1; i < _argc; i++)
177 char *arg = _argv[i];
180 if (strcasecmp(arg, cmd) == 0)
187 //-----------------------------------------------------------------------------------------------------------------------
191 static void sdlEventProc(const SDL_Event &e, Game &game)
195 case SDL_MOUSEMOTION:
196 game.deltah += e.motion.xrel;
197 game.deltav += e.motion.yrel;
201 if ((e.key.keysym.sym == SDLK_g) &&
202 (e.key.keysym.mod & KMOD_CTRL) &&
203 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
204 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
205 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
206 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
213 // --------------------------------------------------------------------------
215 static Point gMidPoint;
217 Boolean SetUp (Game & game)
230 DefaultSettings(game);
232 if (!SDL_WasInit(SDL_INIT_VIDEO))
233 if (SDL_Init(SDL_INIT_VIDEO) == -1)
235 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
238 if(!LoadSettings(game)) {
239 fprintf(stderr, "Failed to load config, creating default\n");
242 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
246 if (SDL_GL_LoadLibrary(NULL) == -1)
248 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
253 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
254 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
255 res = hardcoded_resolutions;
257 // reverse list (it was sorted biggest to smallest by SDL)...
259 for (count = 0; res[count]; count++)
261 if ((res[count]->w < 640) || (res[count]->h < 480))
262 break; // sane lower limit.
265 static SDL_Rect *resolutions_block = NULL;
266 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
267 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
268 if ((resolutions_block == NULL) || (resolutions == NULL))
271 fprintf(stderr, "Out of memory!\n");
275 resolutions[count--] = NULL;
276 for (int i = 0; count >= 0; i++, count--)
278 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
279 resolutions[count] = &resolutions_block[count];
282 if (cmdline("showresolutions"))
284 printf("Resolutions we think are okay:\n");
285 for (int i = 0; resolutions[i]; i++)
286 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
289 Uint32 sdlflags = SDL_OPENGL;
290 if (!cmdline("windowed"))
291 sdlflags |= SDL_FULLSCREEN;
293 SDL_WM_SetCaption("Lugaru", "Lugaru");
297 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
298 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
299 SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
301 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
303 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
304 fprintf(stderr, "forcing 640x480...\n");
306 kContextHeight = 480;
307 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
309 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
310 fprintf(stderr, "forcing 640x480 windowed mode...\n");
311 sdlflags &= ~SDL_FULLSCREEN;
312 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
314 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
321 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
323 fprintf(stderr, "Failed to get double buffered GL context!\n");
328 if (!lookup_all_glsyms())
334 if (!cmdline("nomousegrab"))
335 SDL_WM_GrabInput(SDL_GRAB_ON);
338 glClear( GL_COLOR_BUFFER_BIT );
342 glDisable( GL_ALPHA_TEST);
343 glDisable( GL_BLEND);
344 glDisable( GL_DEPTH_TEST);
345 // glDisable( GL_DITHER);
347 glDisable( GL_LIGHTING);
348 glDisable( GL_LOGIC_OP);
349 glDisable( GL_TEXTURE_1D);
350 glDisable( GL_TEXTURE_2D);
351 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
352 glPixelTransferi( GL_RED_SCALE, 1);
353 glPixelTransferi( GL_RED_BIAS, 0);
354 glPixelTransferi( GL_GREEN_SCALE, 1);
355 glPixelTransferi( GL_GREEN_BIAS, 0);
356 glPixelTransferi( GL_BLUE_SCALE, 1);
357 glPixelTransferi( GL_BLUE_BIAS, 0);
358 glPixelTransferi( GL_ALPHA_SCALE, 1);
359 glPixelTransferi( GL_ALPHA_BIAS, 0);
361 // set initial rendering states
362 glShadeModel( GL_SMOOTH);
364 glDepthFunc( GL_LEQUAL);
365 glDepthMask( GL_TRUE);
366 // glDepthRange( FRONT_CLIP, BACK_CLIP);
367 glEnable( GL_DEPTH_TEST);
368 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
369 glCullFace( GL_FRONT);
370 glEnable( GL_CULL_FACE);
371 glEnable( GL_LIGHTING);
372 // glEnable( GL_LIGHT_MODEL_AMBIENT);
373 glEnable( GL_DITHER);
374 glEnable( GL_COLOR_MATERIAL);
375 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
376 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
377 glAlphaFunc( GL_GREATER, 0.5f);
379 GLint width = kContextWidth;
380 GLint height = kContextHeight;
381 gMidPoint.h = width / 2;
382 gMidPoint.v = height / 2;
386 game.newdetail=detail;
387 game.newscreenwidth=screenwidth;
388 game.newscreenheight=screenheight;
390 if ( CanInitStereo(stereomode) ) {
391 InitStereo(stereomode);
393 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
394 stereomode = stereoNone;
403 static void DoMouse(Game & game)
406 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
408 game.deltah *= usermousesensitivity;
409 game.deltav *= usermousesensitivity;
410 game.mousecoordh += game.deltah;
411 game.mousecoordv += game.deltav;
412 if (game.mousecoordh < 0)
413 game.mousecoordh = 0;
414 else if (game.mousecoordh >= kContextWidth)
415 game.mousecoordh = kContextWidth - 1;
416 if (game.mousecoordv < 0)
417 game.mousecoordv = 0;
418 else if (game.mousecoordv >= kContextHeight)
419 game.mousecoordv = kContextHeight - 1;
424 void DoFrameRate (int update)
426 static long frames = 0;
428 static AbsoluteTime time = {0,0};
429 static AbsoluteTime frametime = {0,0};
430 AbsoluteTime currTime = UpTime ();
431 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
433 if (0 > deltaTime) // if negative microseconds
434 deltaTime /= -1000000.0;
435 else // else milliseconds
438 multiplier=deltaTime;
439 if(multiplier<.001) multiplier=.001;
440 if(multiplier>10) multiplier=10;
441 if(update) frametime = currTime; // reset for next time interval
443 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
445 if (0 > deltaTime) // if negative microseconds
446 deltaTime /= -1000000.0;
447 else // else milliseconds
450 if (0.001 <= deltaTime) // has update interval passed
453 time = currTime; // reset for next time interval
460 void DoUpdate (Game & game)
462 static float sps=200;
464 static float oldmult;
467 if(multiplier>.6)multiplier=.6;
469 game.fps=1/multiplier;
471 count = multiplier*sps;
474 realmultiplier=multiplier;
475 multiplier*=gamespeed;
476 if(difficulty==1)multiplier*=.9;
477 if(difficulty==0)multiplier*=.8;
479 if(game.loading==4)multiplier*=.00001;
480 if(slomo&&!mainmenu)multiplier*=slomospeed;
482 multiplier/=(float)count;
488 for(int i=0;i<count;i++)
494 game.TickOnceAfter();
495 /* - Debug code to test how many channels were active on average per frame
496 static long frames = 0;
498 static AbsoluteTime start = {0,0};
499 AbsoluteTime currTime = UpTime ();
500 static int num_channels = 0;
502 num_channels += OPENAL_GetChannelsPlaying();
503 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
505 if (0 > deltaTime) // if negative microseconds
506 deltaTime /= -1000000.0;
507 else // else milliseconds
515 float avg_channels = (float)num_channels / (float)frames;
517 ofstream opstream("log.txt",ios::app);
518 opstream << "Average frame count: ";
520 opstream << " frames - ";
521 opstream << avg_channels;
522 opstream << " per frame.\n";
532 // --------------------------------------------------------------------------
540 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
543 // cheat here...static destructors are calling glDeleteTexture() after
544 // the context is destroyed and libGL unloaded by SDL_Quit().
545 pglDeleteTextures = glDeleteTextures_doNothing;
549 // --------------------------------------------------------------------------
551 static bool IsFocused()
553 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
559 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
560 static char *findBinaryInPath(const char *bin, char *envr)
562 size_t alloc_size = 0;
570 ptr = strchr(start, ':'); /* find next $PATH separator. */
574 size = strlen(start) + strlen(bin) + 2;
575 if (size > alloc_size)
577 char *x = (char *) realloc(exe, size);
589 /* build full binary path... */
591 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
595 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
597 strcpy(exe, start); /* i'm lazy. piss off. */
601 start = ptr + 1; /* start points to beginning of next element. */
602 } while (ptr != NULL);
607 return(NULL); /* doesn't exist in path. */
608 } /* findBinaryInPath */
611 char *calcBaseDir(const char *argv0)
613 /* If there isn't a path on argv0, then look through the $PATH for it. */
617 const char *ptr = strrchr((char *)argv0, '/');
618 if (strchr(argv0, '/'))
620 retval = strdup(argv0);
622 *((char *) strrchr(retval, '/')) = '\0';
626 envr = getenv("PATH");
627 if (!envr) return NULL;
629 if (!envr) return NULL;
630 retval = findBinaryInPath(argv0, envr);
635 static inline void chdirToAppPath(const char *argv0)
637 char *dir = calcBaseDir(argv0);
640 #if (defined(__APPLE__) && defined(__MACH__))
641 // Chop off /Contents/MacOS if it's at the end of the string, so we
642 // land in the base of the app bundle.
643 const size_t len = strlen(dir);
644 const char *bundledirs = "/Contents/MacOS";
645 const size_t bundledirslen = strlen(bundledirs);
646 if (len > bundledirslen)
648 char *ptr = (dir + len) - bundledirslen;
649 if (strcasecmp(ptr, bundledirs) == 0)
660 int main(int argc, char **argv)
667 // !!! FIXME: we could use a Win32 API for this. --ryan.
669 chdirToAppPath(argv[0]);
680 //ofstream os("error.txt");
682 //ofstream os("log.txt");
688 while (!gDone&&!game.quit&&(!game.tryquit))
694 // check windows messages
699 if(!game.isWaiting()) {
701 while( SDL_PollEvent( &e ) )
703 if( e.type == SDL_QUIT )
708 sdlEventProc(e, game);
719 // allow game chance to pause
724 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
726 SDL_WaitEvent((SDL_Event*)&evt);
727 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
729 else if (evt.type == SDL_QUIT)
741 catch (const std::exception& error)
745 std::string e = "Caught exception: ";
750 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
760 // --------------------------------------------------------------------------
763 bool LoadImage(const char * fname, TGAImageRec & tex)
765 if ( tex.data == NULL )
768 return load_image(fname, tex);
771 void ScreenShot(const char * fname)
778 static bool load_image(const char *file_name, TGAImageRec &tex)
780 const char *ptr = strrchr((char *)file_name, '.');
783 if (strcasecmp(ptr+1, "png") == 0)
784 return load_png(file_name, tex);
785 else if (strcasecmp(ptr+1, "jpg") == 0)
786 return load_jpg(file_name, tex);
789 STUBBED("Unsupported image type");
794 struct my_error_mgr {
795 struct jpeg_error_mgr pub; /* "public" fields */
796 jmp_buf setjmp_buffer; /* for return to caller */
798 typedef struct my_error_mgr * my_error_ptr;
801 static void my_error_exit(j_common_ptr cinfo)
803 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
804 longjmp(err->setjmp_buffer, 1);
807 /* stolen from public domain example.c code in libjpg distribution. */
808 static bool load_jpg(const char *file_name, TGAImageRec &tex)
810 struct jpeg_decompress_struct cinfo;
811 struct my_error_mgr jerr;
812 JSAMPROW buffer[1]; /* Output row buffer */
813 int row_stride; /* physical row width in output buffer */
814 FILE *infile = fopen(file_name, "rb");
819 cinfo.err = jpeg_std_error(&jerr.pub);
820 jerr.pub.error_exit = my_error_exit;
821 if (setjmp(jerr.setjmp_buffer)) {
822 jpeg_destroy_decompress(&cinfo);
827 jpeg_create_decompress(&cinfo);
828 jpeg_stdio_src(&cinfo, infile);
829 (void) jpeg_read_header(&cinfo, TRUE);
831 cinfo.out_color_space = JCS_RGB;
832 cinfo.quantize_colors = 0;
833 (void) jpeg_calc_output_dimensions(&cinfo);
834 (void) jpeg_start_decompress(&cinfo);
836 row_stride = cinfo.output_width * cinfo.output_components;
837 tex.sizeX = cinfo.output_width;
838 tex.sizeY = cinfo.output_height;
841 while (cinfo.output_scanline < cinfo.output_height) {
842 buffer[0] = (JSAMPROW)(char *)tex.data +
843 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
844 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
847 (void) jpeg_finish_decompress(&cinfo);
848 jpeg_destroy_decompress(&cinfo);
855 /* stolen from public domain example.c code in libpng distribution. */
856 static bool load_png(const char *file_name, TGAImageRec &tex)
858 bool hasalpha = false;
859 png_structp png_ptr = NULL;
860 png_infop info_ptr = NULL;
861 png_uint_32 width, height;
862 int bit_depth, color_type, interlace_type;
863 png_byte **rows = NULL;
865 png_byte **row_pointers = NULL;
866 FILE *fp = fopen(file_name, "rb");
871 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
875 info_ptr = png_create_info_struct(png_ptr);
876 if (info_ptr == NULL)
879 if (setjmp(png_jmpbuf(png_ptr)))
882 png_init_io(png_ptr, fp);
883 png_read_png(png_ptr, info_ptr,
884 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
886 png_get_IHDR(png_ptr, info_ptr, &width, &height,
887 &bit_depth, &color_type, &interlace_type, NULL, NULL);
889 if (bit_depth != 8) // transform SHOULD handle this...
892 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
895 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
898 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
899 row_pointers = png_get_rows(png_ptr, info_ptr);
905 png_byte *dst = tex.data;
906 for (int i = height-1; i >= 0; i--)
908 png_byte *src = row_pointers[i];
909 for (int j = 0; j < width; j++)
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);
935 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
942 bool save_image(const char *file_name)
944 const char *ptr = strrchr((char *)file_name, '.');
947 if (strcasecmp(ptr+1, "png") == 0)
948 return save_png(file_name);
951 STUBBED("Unsupported image type");
956 static bool save_png(const char *file_name)
959 png_structp png_ptr = NULL;
960 png_infop info_ptr = NULL;
963 fp = fopen(file_name, "wb");
967 png_bytep *row_pointers = new png_bytep[kContextHeight];
968 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
969 if ((!screenshot) || (!row_pointers))
973 glReadPixels(0, 0, kContextWidth, kContextHeight,
974 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
975 if (glGetError() != GL_NO_ERROR)
978 for (int i = 0; i < kContextHeight; i++)
979 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
981 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
985 info_ptr = png_create_info_struct(png_ptr);
986 if (info_ptr == NULL)
989 if (setjmp(png_jmpbuf(png_ptr)))
992 png_init_io(png_ptr, fp);
994 if (setjmp(png_jmpbuf(png_ptr)))
997 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
998 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
999 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1001 png_write_info(png_ptr, info_ptr);
1003 if (setjmp(png_jmpbuf(png_ptr)))
1006 png_write_image(png_ptr, row_pointers);
1008 if (setjmp(png_jmpbuf(png_ptr)))
1011 png_write_end(png_ptr, NULL);
1015 png_destroy_write_struct(&png_ptr, &info_ptr);
1016 delete[] screenshot;
1017 delete[] row_pointers;
1021 unlink(ConvertFileName(file_name));