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 texdetail;
73 extern bool stillloading;
75 /*extern*/ bool gameFocused;
77 extern float slomospeed;
78 extern float slomofreq;
88 #include "MacCompatibility.h"
93 #include "win-res/resource.h"
98 SDL_Rect **resolutions = NULL;
99 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
100 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
101 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
102 static SDL_Rect *hardcoded_resolutions[] = {
109 void DrawGL(Game & game);
111 Boolean SetUp (Game & game);
112 void DoUpdate (Game & game);
116 // statics/globals (internal only) ------------------------------------------
119 #pragma warning(push)
120 #pragma warning(disable: 4273)
123 #define GL_FUNC(ret,fn,params,call,rt) \
125 static ret (GLAPIENTRY *p##fn) params = NULL; \
126 ret GLAPIENTRY fn params { rt p##fn call; } \
135 static bool lookup_glsym(const char *funcname, void **func)
137 *func = SDL_GL_GetProcAddress(funcname);
140 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
146 static bool lookup_all_glsyms(void)
149 #define GL_FUNC(ret,fn,params,call,rt) \
150 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
156 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
164 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
171 Boolean gDone = false;
176 static int _argc = 0;
177 static char **_argv = NULL;
180 bool cmdline(const char *cmd)
182 for (int i = 1; i < _argc; i++)
184 char *arg = _argv[i];
187 if (strcasecmp(arg, cmd) == 0)
194 //-----------------------------------------------------------------------------------------------------------------------
198 static void sdlEventProc(const SDL_Event &e, Game &game)
202 case SDL_MOUSEMOTION:
203 game.deltah += e.motion.xrel;
204 game.deltav += e.motion.yrel;
208 if ((e.key.keysym.sym == SDLK_g) &&
209 (e.key.keysym.mod & KMOD_CTRL) &&
210 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
211 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
212 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
213 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
220 // --------------------------------------------------------------------------
222 static Point gMidPoint;
224 Boolean SetUp (Game & game)
237 DefaultSettings(game);
239 if (!SDL_WasInit(SDL_INIT_VIDEO))
240 if (SDL_Init(SDL_INIT_VIDEO) == -1)
242 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
245 if(!LoadSettings(game)) {
246 fprintf(stderr, "Failed to load config, creating default\n");
249 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
253 if (SDL_GL_LoadLibrary(NULL) == -1)
255 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
260 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
261 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
262 res = hardcoded_resolutions;
264 // reverse list (it was sorted biggest to smallest by SDL)...
266 for (count = 0; res[count]; count++)
268 if ((res[count]->w < 640) || (res[count]->h < 480))
269 break; // sane lower limit.
272 static SDL_Rect *resolutions_block = NULL;
273 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
274 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
275 if ((resolutions_block == NULL) || (resolutions == NULL))
278 fprintf(stderr, "Out of memory!\n");
282 resolutions[count--] = NULL;
283 for (int i = 0; count >= 0; i++, count--)
285 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
286 resolutions[count] = &resolutions_block[count];
289 if (cmdline("showresolutions"))
291 printf("Resolutions we think are okay:\n");
292 for (int i = 0; resolutions[i]; i++)
293 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
296 Uint32 sdlflags = SDL_OPENGL;
297 if (!cmdline("windowed"))
298 sdlflags |= SDL_FULLSCREEN;
300 SDL_WM_SetCaption("Lugaru", "Lugaru");
304 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
305 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
307 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
309 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
310 fprintf(stderr, "forcing 640x480...\n");
312 kContextHeight = 480;
313 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
315 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
316 fprintf(stderr, "forcing 640x480 windowed mode...\n");
317 sdlflags &= ~SDL_FULLSCREEN;
318 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
320 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
327 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
329 fprintf(stderr, "Failed to get double buffered GL context!\n");
334 if (!lookup_all_glsyms())
340 if (!cmdline("nomousegrab"))
341 SDL_WM_GrabInput(SDL_GRAB_ON);
344 glClear( GL_COLOR_BUFFER_BIT );
348 glDisable( GL_ALPHA_TEST);
349 glDisable( GL_BLEND);
350 glDisable( GL_DEPTH_TEST);
351 // glDisable( GL_DITHER);
353 glDisable( GL_LIGHTING);
354 glDisable( GL_LOGIC_OP);
355 glDisable( GL_TEXTURE_1D);
356 glDisable( GL_TEXTURE_2D);
357 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
358 glPixelTransferi( GL_RED_SCALE, 1);
359 glPixelTransferi( GL_RED_BIAS, 0);
360 glPixelTransferi( GL_GREEN_SCALE, 1);
361 glPixelTransferi( GL_GREEN_BIAS, 0);
362 glPixelTransferi( GL_BLUE_SCALE, 1);
363 glPixelTransferi( GL_BLUE_BIAS, 0);
364 glPixelTransferi( GL_ALPHA_SCALE, 1);
365 glPixelTransferi( GL_ALPHA_BIAS, 0);
367 // set initial rendering states
368 glShadeModel( GL_SMOOTH);
370 glDepthFunc( GL_LEQUAL);
371 glDepthMask( GL_TRUE);
372 // glDepthRange( FRONT_CLIP, BACK_CLIP);
373 glEnable( GL_DEPTH_TEST);
374 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
375 glCullFace( GL_FRONT);
376 glEnable( GL_CULL_FACE);
377 glEnable( GL_LIGHTING);
378 // glEnable( GL_LIGHT_MODEL_AMBIENT);
379 glEnable( GL_DITHER);
380 glEnable( GL_COLOR_MATERIAL);
381 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
382 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
383 glAlphaFunc( GL_GREATER, 0.5f);
385 GLint width = kContextWidth;
386 GLint height = kContextHeight;
387 gMidPoint.h = width / 2;
388 gMidPoint.v = height / 2;
392 game.newdetail=detail;
393 game.newscreenwidth=screenwidth;
394 game.newscreenheight=screenheight;
396 if ( CanInitStereo(stereomode) ) {
397 InitStereo(stereomode);
399 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
400 stereomode = stereoNone;
409 static void DoMouse(Game & game)
412 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
414 game.deltah *= usermousesensitivity;
415 game.deltav *= usermousesensitivity;
416 game.mousecoordh += game.deltah;
417 game.mousecoordv += game.deltav;
418 if (game.mousecoordh < 0)
419 game.mousecoordh = 0;
420 else if (game.mousecoordh >= kContextWidth)
421 game.mousecoordh = kContextWidth - 1;
422 if (game.mousecoordv < 0)
423 game.mousecoordv = 0;
424 else if (game.mousecoordv >= kContextHeight)
425 game.mousecoordv = kContextHeight - 1;
430 void DoFrameRate (int update)
432 static long frames = 0;
434 static AbsoluteTime time = {0,0};
435 static AbsoluteTime frametime = {0,0};
436 AbsoluteTime currTime = UpTime ();
437 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
439 if (0 > deltaTime) // if negative microseconds
440 deltaTime /= -1000000.0;
441 else // else milliseconds
444 multiplier=deltaTime;
445 if(multiplier<.001) multiplier=.001;
446 if(multiplier>10) multiplier=10;
447 if(update) frametime = currTime; // reset for next time interval
449 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
451 if (0 > deltaTime) // if negative microseconds
452 deltaTime /= -1000000.0;
453 else // else milliseconds
456 if (0.001 <= deltaTime) // has update interval passed
459 time = currTime; // reset for next time interval
466 void DoUpdate (Game & game)
468 static float sps=200;
470 static float oldmult;
473 if(multiplier>.6)multiplier=.6;
475 game.fps=1/multiplier;
477 count = multiplier*sps;
480 realmultiplier=multiplier;
481 multiplier*=gamespeed;
482 if(difficulty==1)multiplier*=.9;
483 if(difficulty==0)multiplier*=.8;
485 if(game.loading==4)multiplier*=.00001;
486 if(slomo&&!mainmenu)multiplier*=slomospeed;
488 multiplier/=(float)count;
494 for(int i=0;i<count;i++)
500 game.TickOnceAfter();
501 /* - Debug code to test how many channels were active on average per frame
502 static long frames = 0;
504 static AbsoluteTime start = {0,0};
505 AbsoluteTime currTime = UpTime ();
506 static int num_channels = 0;
508 num_channels += OPENAL_GetChannelsPlaying();
509 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
511 if (0 > deltaTime) // if negative microseconds
512 deltaTime /= -1000000.0;
513 else // else milliseconds
521 float avg_channels = (float)num_channels / (float)frames;
523 ofstream opstream("log.txt",ios::app);
524 opstream << "Average frame count: ";
526 opstream << " frames - ";
527 opstream << avg_channels;
528 opstream << " per frame.\n";
538 // --------------------------------------------------------------------------
546 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
549 // cheat here...static destructors are calling glDeleteTexture() after
550 // the context is destroyed and libGL unloaded by SDL_Quit().
551 pglDeleteTextures = glDeleteTextures_doNothing;
555 // --------------------------------------------------------------------------
557 static bool IsFocused()
559 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
565 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
566 static char *findBinaryInPath(const char *bin, char *envr)
568 size_t alloc_size = 0;
576 ptr = strchr(start, ':'); /* find next $PATH separator. */
580 size = strlen(start) + strlen(bin) + 2;
581 if (size > alloc_size)
583 char *x = (char *) realloc(exe, size);
595 /* build full binary path... */
597 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
601 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
603 strcpy(exe, start); /* i'm lazy. piss off. */
607 start = ptr + 1; /* start points to beginning of next element. */
608 } while (ptr != NULL);
613 return(NULL); /* doesn't exist in path. */
614 } /* findBinaryInPath */
617 char *calcBaseDir(const char *argv0)
619 /* If there isn't a path on argv0, then look through the $PATH for it. */
623 const char *ptr = strrchr((char *)argv0, '/');
624 if (strchr(argv0, '/'))
626 retval = strdup(argv0);
628 *((char *) strrchr(retval, '/')) = '\0';
632 envr = getenv("PATH");
633 if (!envr) return NULL;
635 if (!envr) return NULL;
636 retval = findBinaryInPath(argv0, envr);
641 static inline void chdirToAppPath(const char *argv0)
643 char *dir = calcBaseDir(argv0);
646 #if (defined(__APPLE__) && defined(__MACH__))
647 // Chop off /Contents/MacOS if it's at the end of the string, so we
648 // land in the base of the app bundle.
649 const size_t len = strlen(dir);
650 const char *bundledirs = "/Contents/MacOS";
651 const size_t bundledirslen = strlen(bundledirs);
652 if (len > bundledirslen)
654 char *ptr = (dir + len) - bundledirslen;
655 if (strcasecmp(ptr, bundledirs) == 0)
666 int main(int argc, char **argv)
673 // !!! FIXME: we could use a Win32 API for this. --ryan.
675 chdirToAppPath(argv[0]);
686 //ofstream os("error.txt");
688 //ofstream os("log.txt");
694 while (!gDone&&!game.quit&&(!game.tryquit))
700 // check windows messages
705 if(!game.isWaiting()) {
707 while( SDL_PollEvent( &e ) )
709 if( e.type == SDL_QUIT )
714 sdlEventProc(e, game);
725 // allow game chance to pause
730 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
732 SDL_WaitEvent((SDL_Event*)&evt);
733 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
735 else if (evt.type == SDL_QUIT)
747 catch (const std::exception& error)
751 std::string e = "Caught exception: ";
756 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
766 // --------------------------------------------------------------------------
769 bool LoadImage(const char * fname, TGAImageRec & tex)
771 if ( tex.data == NULL )
774 return load_image(fname, tex);
777 void ScreenShot(const char * fname)
784 static bool load_image(const char *file_name, TGAImageRec &tex)
786 const char *ptr = strrchr((char *)file_name, '.');
789 if (strcasecmp(ptr+1, "png") == 0)
790 return load_png(file_name, tex);
791 else if (strcasecmp(ptr+1, "jpg") == 0)
792 return load_jpg(file_name, tex);
795 STUBBED("Unsupported image type");
800 struct my_error_mgr {
801 struct jpeg_error_mgr pub; /* "public" fields */
802 jmp_buf setjmp_buffer; /* for return to caller */
804 typedef struct my_error_mgr * my_error_ptr;
807 static void my_error_exit(j_common_ptr cinfo)
809 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
810 longjmp(err->setjmp_buffer, 1);
813 /* stolen from public domain example.c code in libjpg distribution. */
814 static bool load_jpg(const char *file_name, TGAImageRec &tex)
816 struct jpeg_decompress_struct cinfo;
817 struct my_error_mgr jerr;
818 JSAMPROW buffer[1]; /* Output row buffer */
819 int row_stride; /* physical row width in output buffer */
820 FILE *infile = fopen(file_name, "rb");
825 cinfo.err = jpeg_std_error(&jerr.pub);
826 jerr.pub.error_exit = my_error_exit;
827 if (setjmp(jerr.setjmp_buffer)) {
828 jpeg_destroy_decompress(&cinfo);
833 jpeg_create_decompress(&cinfo);
834 jpeg_stdio_src(&cinfo, infile);
835 (void) jpeg_read_header(&cinfo, TRUE);
837 cinfo.out_color_space = JCS_RGB;
838 cinfo.quantize_colors = 0;
839 (void) jpeg_calc_output_dimensions(&cinfo);
840 (void) jpeg_start_decompress(&cinfo);
842 row_stride = cinfo.output_width * cinfo.output_components;
843 tex.sizeX = cinfo.output_width;
844 tex.sizeY = cinfo.output_height;
847 while (cinfo.output_scanline < cinfo.output_height) {
848 buffer[0] = (JSAMPROW)(char *)tex.data +
849 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
850 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
853 (void) jpeg_finish_decompress(&cinfo);
854 jpeg_destroy_decompress(&cinfo);
861 /* stolen from public domain example.c code in libpng distribution. */
862 static bool load_png(const char *file_name, TGAImageRec &tex)
864 bool hasalpha = false;
865 png_structp png_ptr = NULL;
866 png_infop info_ptr = NULL;
867 png_uint_32 width, height;
868 int bit_depth, color_type, interlace_type;
869 png_byte **rows = NULL;
871 png_byte **row_pointers = NULL;
872 FILE *fp = fopen(file_name, "rb");
877 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
881 info_ptr = png_create_info_struct(png_ptr);
882 if (info_ptr == NULL)
885 if (setjmp(png_jmpbuf(png_ptr)))
888 png_init_io(png_ptr, fp);
889 png_read_png(png_ptr, info_ptr,
890 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
892 png_get_IHDR(png_ptr, info_ptr, &width, &height,
893 &bit_depth, &color_type, &interlace_type, NULL, NULL);
895 if (bit_depth != 8) // transform SHOULD handle this...
898 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
901 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
904 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
905 row_pointers = png_get_rows(png_ptr, info_ptr);
911 png_byte *dst = tex.data;
912 for (int i = height-1; i >= 0; i--)
914 png_byte *src = row_pointers[i];
915 for (int j = 0; j < width; j++)
929 png_byte *dst = tex.data;
930 int pitch = width * 4;
931 for (int i = height-1; i >= 0; i--, dst += pitch)
932 memcpy(dst, row_pointers[i], pitch);
941 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
948 bool save_image(const char *file_name)
950 const char *ptr = strrchr((char *)file_name, '.');
953 if (strcasecmp(ptr+1, "png") == 0)
954 return save_png(file_name);
957 STUBBED("Unsupported image type");
962 static bool save_png(const char *file_name)
965 png_structp png_ptr = NULL;
966 png_infop info_ptr = NULL;
969 fp = fopen(file_name, "wb");
973 png_bytep *row_pointers = new png_bytep[kContextHeight];
974 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
975 if ((!screenshot) || (!row_pointers))
979 glReadPixels(0, 0, kContextWidth, kContextHeight,
980 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
981 if (glGetError() != GL_NO_ERROR)
984 for (int i = 0; i < kContextHeight; i++)
985 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
987 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
991 info_ptr = png_create_info_struct(png_ptr);
992 if (info_ptr == NULL)
995 if (setjmp(png_jmpbuf(png_ptr)))
998 png_init_io(png_ptr, fp);
1000 if (setjmp(png_jmpbuf(png_ptr)))
1003 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1004 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1005 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1007 png_write_info(png_ptr, info_ptr);
1009 if (setjmp(png_jmpbuf(png_ptr)))
1012 png_write_image(png_ptr, row_pointers);
1014 if (setjmp(png_jmpbuf(png_ptr)))
1017 png_write_end(png_ptr, NULL);
1021 png_destroy_write_struct(&png_ptr, &info_ptr);
1022 delete[] screenshot;
1023 delete[] row_pointers;
1027 unlink(ConvertFileName(file_name));