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 //-----------------------------------------------------------------------------------------------------------------------
192 glClear( GL_COLOR_BUFFER_BIT );
196 glDisable( GL_ALPHA_TEST);
197 glDisable( GL_BLEND);
198 glDisable( GL_DEPTH_TEST);
199 // glDisable( GL_DITHER);
201 glDisable( GL_LIGHTING);
202 glDisable( GL_LOGIC_OP);
203 glDisable( GL_TEXTURE_1D);
204 glDisable( GL_TEXTURE_2D);
205 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
206 glPixelTransferi( GL_RED_SCALE, 1);
207 glPixelTransferi( GL_RED_BIAS, 0);
208 glPixelTransferi( GL_GREEN_SCALE, 1);
209 glPixelTransferi( GL_GREEN_BIAS, 0);
210 glPixelTransferi( GL_BLUE_SCALE, 1);
211 glPixelTransferi( GL_BLUE_BIAS, 0);
212 glPixelTransferi( GL_ALPHA_SCALE, 1);
213 glPixelTransferi( GL_ALPHA_BIAS, 0);
215 // set initial rendering states
216 glShadeModel( GL_SMOOTH);
218 glDepthFunc( GL_LEQUAL);
219 glDepthMask( GL_TRUE);
220 // glDepthRange( FRONT_CLIP, BACK_CLIP);
221 glEnable( GL_DEPTH_TEST);
222 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
223 glCullFace( GL_FRONT);
224 glEnable( GL_CULL_FACE);
225 glEnable( GL_LIGHTING);
226 // glEnable( GL_LIGHT_MODEL_AMBIENT);
227 glEnable( GL_DITHER);
228 glEnable( GL_COLOR_MATERIAL);
229 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
230 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
231 glAlphaFunc( GL_GREATER, 0.5f);
233 if ( CanInitStereo(stereomode) ) {
234 InitStereo(stereomode);
236 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
237 stereomode = stereoNone;
241 static void toggleFullscreen(){
242 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
243 //~ SDL_Surface* screen=SDL_GetVideoSurface();
244 //~ Uint32 flags=screen->flags;
245 //~ screen=SDL_SetVideoMode(0,0,0,flags^SDL_FULLSCREEN);
247 //~ screen=SDL_SetVideoMode(0,0,0,flags);
250 //~ //reload opengl state
252 //~ for(std::vector<TextureInfo>::iterator it=Game::textures.begin(); it!=Game::textures.end(); it++) {
255 //~ pgame->text.BuildFont();
256 //~ pgame->LoadScreenTexture();
259 static void sdlEventProc(const SDL_Event &e, Game &game)
262 case SDL_MOUSEMOTION:
263 game.deltah += e.motion.xrel;
264 game.deltav += e.motion.yrel;
268 if ((e.key.keysym.sym == SDLK_g) &&
269 (e.key.keysym.mod & KMOD_CTRL) &&
270 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
271 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
272 } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
281 // --------------------------------------------------------------------------
283 static Point gMidPoint;
285 Boolean SetUp (Game & game)
298 DefaultSettings(game);
300 if (!SDL_WasInit(SDL_INIT_VIDEO))
301 if (SDL_Init(SDL_INIT_VIDEO) == -1)
303 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
306 if(!LoadSettings(game)) {
307 fprintf(stderr, "Failed to load config, creating default\n");
310 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
314 if (SDL_GL_LoadLibrary(NULL) == -1)
316 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
321 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
322 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
323 res = hardcoded_resolutions;
325 // reverse list (it was sorted biggest to smallest by SDL)...
327 for (count = 0; res[count]; count++)
329 if ((res[count]->w < 640) || (res[count]->h < 480))
330 break; // sane lower limit.
333 static SDL_Rect *resolutions_block = NULL;
334 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
335 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
336 if ((resolutions_block == NULL) || (resolutions == NULL))
339 fprintf(stderr, "Out of memory!\n");
343 resolutions[count--] = NULL;
344 for (int i = 0; count >= 0; i++, count--)
346 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
347 resolutions[count] = &resolutions_block[count];
350 if (cmdline("showresolutions"))
352 printf("Resolutions we think are okay:\n");
353 for (int i = 0; resolutions[i]; i++)
354 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
357 Uint32 sdlflags = SDL_OPENGL;
359 if (!cmdline("windowed"))
360 sdlflags |= SDL_FULLSCREEN;
362 SDL_WM_SetCaption("Lugaru", "Lugaru");
366 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
367 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
368 #if SDL_VERSION_ATLEAST(1, 2, 10)
369 SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
372 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
374 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
375 fprintf(stderr, "forcing 640x480...\n");
377 kContextHeight = 480;
378 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
380 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
381 fprintf(stderr, "forcing 640x480 windowed mode...\n");
382 sdlflags &= ~SDL_FULLSCREEN;
383 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
385 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
392 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
394 fprintf(stderr, "Failed to get double buffered GL context!\n");
399 if (!lookup_all_glsyms())
405 if (!cmdline("nomousegrab"))
406 SDL_WM_GrabInput(SDL_GRAB_ON);
411 GLint width = kContextWidth;
412 GLint height = kContextHeight;
413 gMidPoint.h = width / 2;
414 gMidPoint.v = height / 2;
418 game.newdetail=detail;
419 game.newscreenwidth=screenwidth;
420 game.newscreenheight=screenheight;
428 static void DoMouse(Game & game)
431 if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
433 game.deltah *= usermousesensitivity;
434 game.deltav *= usermousesensitivity;
435 game.mousecoordh += game.deltah;
436 game.mousecoordv += game.deltav;
437 if (game.mousecoordh < 0)
438 game.mousecoordh = 0;
439 else if (game.mousecoordh >= kContextWidth)
440 game.mousecoordh = kContextWidth - 1;
441 if (game.mousecoordv < 0)
442 game.mousecoordv = 0;
443 else if (game.mousecoordv >= kContextHeight)
444 game.mousecoordv = kContextHeight - 1;
449 void DoFrameRate (int update)
451 static long frames = 0;
453 static AbsoluteTime time = {0,0};
454 static AbsoluteTime frametime = {0,0};
455 AbsoluteTime currTime = UpTime ();
456 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
458 if (0 > deltaTime) // if negative microseconds
459 deltaTime /= -1000000.0;
460 else // else milliseconds
463 multiplier=deltaTime;
464 if(multiplier<.001) multiplier=.001;
465 if(multiplier>10) multiplier=10;
466 if(update) frametime = currTime; // reset for next time interval
468 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
470 if (0 > deltaTime) // if negative microseconds
471 deltaTime /= -1000000.0;
472 else // else milliseconds
475 if (0.001 <= deltaTime) // has update interval passed
478 time = currTime; // reset for next time interval
485 void DoUpdate (Game & game)
487 static float sps=200;
489 static float oldmult;
492 if(multiplier>.6)multiplier=.6;
494 game.fps=1/multiplier;
496 count = multiplier*sps;
499 realmultiplier=multiplier;
500 multiplier*=gamespeed;
501 if(difficulty==1)multiplier*=.9;
502 if(difficulty==0)multiplier*=.8;
504 if(game.loading==4)multiplier*=.00001;
505 if(slomo&&!mainmenu)multiplier*=slomospeed;
507 multiplier/=(float)count;
513 for(int i=0;i<count;i++)
519 game.TickOnceAfter();
520 /* - Debug code to test how many channels were active on average per frame
521 static long frames = 0;
523 static AbsoluteTime start = {0,0};
524 AbsoluteTime currTime = UpTime ();
525 static int num_channels = 0;
527 num_channels += OPENAL_GetChannelsPlaying();
528 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
530 if (0 > deltaTime) // if negative microseconds
531 deltaTime /= -1000000.0;
532 else // else milliseconds
540 float avg_channels = (float)num_channels / (float)frames;
542 ofstream opstream("log.txt",ios::app);
543 opstream << "Average frame count: ";
545 opstream << " frames - ";
546 opstream << avg_channels;
547 opstream << " per frame.\n";
557 // --------------------------------------------------------------------------
565 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
568 // cheat here...static destructors are calling glDeleteTexture() after
569 // the context is destroyed and libGL unloaded by SDL_Quit().
570 pglDeleteTextures = glDeleteTextures_doNothing;
574 // --------------------------------------------------------------------------
576 static bool IsFocused()
578 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
584 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
585 static char *findBinaryInPath(const char *bin, char *envr)
587 size_t alloc_size = 0;
595 ptr = strchr(start, ':'); /* find next $PATH separator. */
599 size = strlen(start) + strlen(bin) + 2;
600 if (size > alloc_size)
602 char *x = (char *) realloc(exe, size);
614 /* build full binary path... */
616 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
620 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
622 strcpy(exe, start); /* i'm lazy. piss off. */
626 start = ptr + 1; /* start points to beginning of next element. */
627 } while (ptr != NULL);
632 return(NULL); /* doesn't exist in path. */
633 } /* findBinaryInPath */
636 char *calcBaseDir(const char *argv0)
638 /* If there isn't a path on argv0, then look through the $PATH for it. */
642 const char *ptr = strrchr((char *)argv0, '/');
643 if (strchr(argv0, '/'))
645 retval = strdup(argv0);
647 *((char *) strrchr(retval, '/')) = '\0';
651 envr = getenv("PATH");
652 if (!envr) return NULL;
654 if (!envr) return NULL;
655 retval = findBinaryInPath(argv0, envr);
660 static inline void chdirToAppPath(const char *argv0)
662 char *dir = calcBaseDir(argv0);
665 #if (defined(__APPLE__) && defined(__MACH__))
666 // Chop off /Contents/MacOS if it's at the end of the string, so we
667 // land in the base of the app bundle.
668 const size_t len = strlen(dir);
669 const char *bundledirs = "/Contents/MacOS";
670 const size_t bundledirslen = strlen(bundledirs);
671 if (len > bundledirslen)
673 char *ptr = (dir + len) - bundledirslen;
674 if (strcasecmp(ptr, bundledirs) == 0)
685 int main(int argc, char **argv)
692 // !!! FIXME: we could use a Win32 API for this. --ryan.
694 chdirToAppPath(argv[0]);
705 //ofstream os("error.txt");
707 //ofstream os("log.txt");
713 while (!gDone&&!game.quit&&(!game.tryquit))
719 // check windows messages
724 if(!game.isWaiting()) {
726 while( SDL_PollEvent( &e ) )
728 if( e.type == SDL_QUIT )
733 sdlEventProc(e, game);
744 // allow game chance to pause
749 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
751 SDL_WaitEvent((SDL_Event*)&evt);
752 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
754 else if (evt.type == SDL_QUIT)
767 catch (const std::exception& error)
771 std::string e = "Caught exception: ";
776 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
786 // --------------------------------------------------------------------------
789 bool LoadImage(const char * fname, TGAImageRec & tex)
791 if ( tex.data == NULL )
794 return load_image(fname, tex);
797 void ScreenShot(const char * fname)
804 static bool load_image(const char *file_name, TGAImageRec &tex)
806 const char *ptr = strrchr((char *)file_name, '.');
809 if (strcasecmp(ptr+1, "png") == 0)
810 return load_png(file_name, tex);
811 else if (strcasecmp(ptr+1, "jpg") == 0)
812 return load_jpg(file_name, tex);
815 STUBBED("Unsupported image type");
820 struct my_error_mgr {
821 struct jpeg_error_mgr pub; /* "public" fields */
822 jmp_buf setjmp_buffer; /* for return to caller */
824 typedef struct my_error_mgr * my_error_ptr;
827 static void my_error_exit(j_common_ptr cinfo)
829 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
830 longjmp(err->setjmp_buffer, 1);
833 /* stolen from public domain example.c code in libjpg distribution. */
834 static bool load_jpg(const char *file_name, TGAImageRec &tex)
836 struct jpeg_decompress_struct cinfo;
837 struct my_error_mgr jerr;
838 JSAMPROW buffer[1]; /* Output row buffer */
839 int row_stride; /* physical row width in output buffer */
840 FILE *infile = fopen(file_name, "rb");
845 cinfo.err = jpeg_std_error(&jerr.pub);
846 jerr.pub.error_exit = my_error_exit;
847 if (setjmp(jerr.setjmp_buffer)) {
848 jpeg_destroy_decompress(&cinfo);
853 jpeg_create_decompress(&cinfo);
854 jpeg_stdio_src(&cinfo, infile);
855 (void) jpeg_read_header(&cinfo, TRUE);
857 cinfo.out_color_space = JCS_RGB;
858 cinfo.quantize_colors = 0;
859 (void) jpeg_calc_output_dimensions(&cinfo);
860 (void) jpeg_start_decompress(&cinfo);
862 row_stride = cinfo.output_width * cinfo.output_components;
863 tex.sizeX = cinfo.output_width;
864 tex.sizeY = cinfo.output_height;
867 while (cinfo.output_scanline < cinfo.output_height) {
868 buffer[0] = (JSAMPROW)(char *)tex.data +
869 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
870 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
873 (void) jpeg_finish_decompress(&cinfo);
874 jpeg_destroy_decompress(&cinfo);
881 /* stolen from public domain example.c code in libpng distribution. */
882 static bool load_png(const char *file_name, TGAImageRec &tex)
884 bool hasalpha = false;
885 png_structp png_ptr = NULL;
886 png_infop info_ptr = NULL;
887 png_uint_32 width, height;
888 int bit_depth, color_type, interlace_type;
889 png_byte **rows = NULL;
891 png_byte **row_pointers = NULL;
892 FILE *fp = fopen(file_name, "rb");
897 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
901 info_ptr = png_create_info_struct(png_ptr);
902 if (info_ptr == NULL)
905 if (setjmp(png_jmpbuf(png_ptr)))
908 png_init_io(png_ptr, fp);
909 png_read_png(png_ptr, info_ptr,
910 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
912 png_get_IHDR(png_ptr, info_ptr, &width, &height,
913 &bit_depth, &color_type, &interlace_type, NULL, NULL);
915 if (bit_depth != 8) // transform SHOULD handle this...
918 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
921 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
924 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
925 row_pointers = png_get_rows(png_ptr, info_ptr);
931 png_byte *dst = tex.data;
932 for (int i = height-1; i >= 0; i--)
934 png_byte *src = row_pointers[i];
935 for (int j = 0; j < width; j++)
949 png_byte *dst = tex.data;
950 int pitch = width * 4;
951 for (int i = height-1; i >= 0; i--, dst += pitch)
952 memcpy(dst, row_pointers[i], pitch);
961 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
968 bool save_image(const char *file_name)
970 const char *ptr = strrchr((char *)file_name, '.');
973 if (strcasecmp(ptr+1, "png") == 0)
974 return save_png(file_name);
977 STUBBED("Unsupported image type");
982 static bool save_png(const char *file_name)
985 png_structp png_ptr = NULL;
986 png_infop info_ptr = NULL;
989 fp = fopen(file_name, "wb");
993 png_bytep *row_pointers = new png_bytep[kContextHeight];
994 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
995 if ((!screenshot) || (!row_pointers))
999 glReadPixels(0, 0, kContextWidth, kContextHeight,
1000 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1001 if (glGetError() != GL_NO_ERROR)
1004 for (int i = 0; i < kContextHeight; i++)
1005 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1007 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1008 if (png_ptr == NULL)
1011 info_ptr = png_create_info_struct(png_ptr);
1012 if (info_ptr == NULL)
1015 if (setjmp(png_jmpbuf(png_ptr)))
1018 png_init_io(png_ptr, fp);
1020 if (setjmp(png_jmpbuf(png_ptr)))
1023 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1024 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1025 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1027 png_write_info(png_ptr, info_ptr);
1029 if (setjmp(png_jmpbuf(png_ptr)))
1032 png_write_image(png_ptr, row_pointers);
1034 if (setjmp(png_jmpbuf(png_ptr)))
1037 png_write_end(png_ptr, NULL);
1041 png_destroy_write_struct(&png_ptr, &info_ptr);
1042 delete[] screenshot;
1043 delete[] row_pointers;
1047 unlink(ConvertFileName(file_name));