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.
35 static bool load_image(const char * fname, TGAImageRec & tex);
36 static bool load_png(const char * fname, TGAImageRec & tex);
37 static bool load_jpg(const char * fname, TGAImageRec & tex);
38 bool save_image(const char * fname);
39 static bool save_png(const char * fname);
42 #include "openal_wrapper.h"
44 extern float multiplier;
46 extern float realmultiplier;
48 extern bool cellophane;
49 extern float texdetail;
53 extern bool stillloading;
58 extern float slomospeed;
59 extern float slomofreq;
70 #include "MacCompatibility.h"
75 #include "win-res/resource.h"
78 extern SDL_Window *sdlwindow;
82 set<pair<int,int>> resolutions;
89 // statics/globals (internal only) ------------------------------------------
93 #pragma warning(disable: 4273)
96 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
97 #define GL_FUNC(ret,fn,params,call,rt) \
99 static ret (GLAPIENTRY *p##fn) params = NULL; \
100 ret GLAPIENTRY fn params { rt p##fn call; } \
104 #endif // __MINGW32__
110 static bool lookup_glsym(const char *funcname, void **func)
112 *func = SDL_GL_GetProcAddress(funcname);
114 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
120 static bool lookup_all_glsyms(void)
123 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
124 #define GL_FUNC(ret,fn,params,call,rt) \
125 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
128 #endif // __MINGW32__
132 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
133 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
137 #endif // __MINGW32__
142 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
149 Boolean gDone = false;
151 static int _argc = 0;
152 static char **_argv = NULL;
154 bool cmdline(const char *cmd)
156 for (int i = 1; i < _argc; i++) {
157 char *arg = _argv[i];
160 if (strcasecmp(arg, cmd) == 0)
167 //-----------------------------------------------------------------------------------------------------------------------
173 glClear( GL_COLOR_BUFFER_BIT );
177 glDisable( GL_ALPHA_TEST);
178 glDisable( GL_BLEND);
179 glDisable( GL_DEPTH_TEST);
180 //glDisable( GL_DITHER);
182 glDisable( GL_LIGHTING);
183 glDisable( GL_LOGIC_OP);
184 glDisable( GL_TEXTURE_1D);
185 glDisable( GL_TEXTURE_2D);
186 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
187 glPixelTransferi( GL_RED_SCALE, 1);
188 glPixelTransferi( GL_RED_BIAS, 0);
189 glPixelTransferi( GL_GREEN_SCALE, 1);
190 glPixelTransferi( GL_GREEN_BIAS, 0);
191 glPixelTransferi( GL_BLUE_SCALE, 1);
192 glPixelTransferi( GL_BLUE_BIAS, 0);
193 glPixelTransferi( GL_ALPHA_SCALE, 1);
194 glPixelTransferi( GL_ALPHA_BIAS, 0);
196 // set initial rendering states
197 glShadeModel( GL_SMOOTH);
199 glDepthFunc( GL_LEQUAL);
200 glDepthMask( GL_TRUE);
201 //glDepthRange( FRONT_CLIP, BACK_CLIP);
202 glEnable( GL_DEPTH_TEST);
203 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
204 glCullFace( GL_FRONT);
205 glEnable( GL_CULL_FACE);
206 glEnable( GL_LIGHTING);
207 //glEnable( GL_LIGHT_MODEL_AMBIENT);
208 glEnable( GL_DITHER);
209 glEnable( GL_COLOR_MATERIAL);
210 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
211 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
212 glAlphaFunc( GL_GREATER, 0.5f);
214 if ( CanInitStereo(stereomode) ) {
215 InitStereo(stereomode);
217 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
218 stereomode = stereoNone;
222 void toggleFullscreen()
224 fullscreen = !fullscreen;
225 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
226 if (flags & SDL_WINDOW_FULLSCREEN) {
227 flags &= ~SDL_WINDOW_FULLSCREEN;
229 flags |= SDL_WINDOW_FULLSCREEN;
231 SDL_SetWindowFullscreen(sdlwindow, flags);
234 static SDL_bool sdlEventProc(const SDL_Event &e)
240 case SDL_WINDOWEVENT:
241 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
246 case SDL_MOUSEMOTION:
247 deltah += e.motion.xrel;
248 deltav += e.motion.yrel;
252 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
253 (e.key.keysym.mod & KMOD_CTRL)) {
254 SDL_bool mode = SDL_TRUE;
255 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
256 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
257 SDL_SetWindowGrab(sdlwindow, mode);
258 SDL_SetRelativeMouseMode(mode);
259 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
269 // --------------------------------------------------------------------------
271 static Point gMidPoint;
285 if (!SDL_WasInit(SDL_INIT_VIDEO))
286 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
287 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
290 if (!LoadSettings()) {
291 fprintf(stderr, "Failed to load config, creating default\n");
294 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
298 if (SDL_GL_LoadLibrary(NULL) == -1) {
299 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
304 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
305 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
306 SDL_DisplayMode mode;
307 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
309 if ((mode.w < 640) || (mode.h < 480))
310 continue; // sane lower limit.
311 pair<int,int> resolution(mode.w, mode.h);
312 resolutions.insert(resolution);
316 if (resolutions.empty()) {
317 const std::string error = "No suitable video resolutions found.";
318 cerr << error << endl;
319 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
324 if (cmdline("showresolutions")) {
325 printf("Available resolutions:\n");
326 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
327 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
331 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
332 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
334 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
335 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
337 sdlflags |= SDL_WINDOW_FULLSCREEN;
339 if (!cmdline("nomousegrab"))
340 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
342 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
343 kContextWidth, kContextHeight, sdlflags);
346 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
347 fprintf(stderr, "forcing 640x480...\n");
349 kContextHeight = 480;
350 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
351 kContextWidth, kContextHeight, sdlflags);
353 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
354 fprintf(stderr, "forcing 640x480 windowed mode...\n");
355 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
356 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
357 kContextWidth, kContextHeight, sdlflags);
360 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
366 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
368 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
373 SDL_GL_MakeCurrent(sdlwindow, glctx);
375 if (!lookup_all_glsyms()) {
376 fprintf(stderr, "Missing required OpenGL functions.\n");
382 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
384 fprintf(stderr, "Failed to get a double-buffered context.\n");
389 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
390 SDL_GL_SetSwapInterval(1);
393 if (!cmdline("nomousegrab"))
394 SDL_SetRelativeMouseMode(SDL_TRUE);
398 GLint width = kContextWidth;
399 GLint height = kContextHeight;
400 gMidPoint.h = width / 2;
401 gMidPoint.v = height / 2;
403 screenheight = height;
406 newscreenwidth = screenwidth;
407 newscreenheight = screenheight;
409 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
410 pair<int,int> startresolution(width,height);
411 if (resolutions.find(startresolution) == resolutions.end()) {
412 resolutions.insert(startresolution);
421 static void DoMouse()
424 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
425 deltah *= usermousesensitivity;
426 deltav *= usermousesensitivity;
427 mousecoordh += deltah;
428 mousecoordv += deltav;
431 else if (mousecoordh >= kContextWidth)
432 mousecoordh = kContextWidth - 1;
435 else if (mousecoordv >= kContextHeight)
436 mousecoordv = kContextHeight - 1;
441 void DoFrameRate (int update)
443 static long frames = 0;
445 static AbsoluteTime time = {0, 0};
446 static AbsoluteTime frametime = {0, 0};
447 AbsoluteTime currTime = UpTime ();
448 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
450 if (0 > deltaTime) // if negative microseconds
451 deltaTime /= -1000000.0;
452 else // else milliseconds
455 multiplier = deltaTime;
456 if (multiplier < .001)
461 frametime = currTime; // reset for next time interval
463 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
465 if (0 > deltaTime) // if negative microseconds
466 deltaTime /= -1000000.0;
467 else // else milliseconds
470 if (0.001 <= deltaTime) { // has update interval passed
472 time = currTime; // reset for next time interval
481 static float sps = 200;
483 static float oldmult;
489 fps = 1 / multiplier;
491 count = multiplier * sps;
495 realmultiplier = multiplier;
496 multiplier *= gamespeed;
503 multiplier *= .00001;
504 if (slomo && !mainmenu)
505 multiplier *= slomospeed;
506 oldmult = multiplier;
507 multiplier /= (float)count;
513 for (int i = 0; i < count; i++) {
516 multiplier = oldmult;
519 /* - Debug code to test how many channels were active on average per frame
520 static long frames = 0;
522 static AbsoluteTime start = {0,0};
523 AbsoluteTime currTime = UpTime ();
524 static int num_channels = 0;
526 num_channels += OPENAL_GetChannelsPlaying();
527 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
529 if (0 > deltaTime) // if negative microseconds
530 deltaTime /= -1000000.0;
531 else // else milliseconds
539 float avg_channels = (float)num_channels / (float)frames;
541 ofstream opstream("log.txt",ios::app);
542 opstream << "Average frame count: ";
544 opstream << " frames - ";
545 opstream << avg_channels;
546 opstream << " per frame.\n";
553 if ( stereomode == stereoNone ) {
554 DrawGLScene(stereoCenter);
556 DrawGLScene(stereoLeft);
557 DrawGLScene(stereoRight);
561 // --------------------------------------------------------------------------
569 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
570 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
573 // cheat here...static destructors are calling glDeleteTexture() after
574 // the context is destroyed and libGL unloaded by SDL_Quit().
575 pglDeleteTextures = glDeleteTextures_doNothing;
576 #endif // __MINGW32__
580 // --------------------------------------------------------------------------
582 static bool IsFocused()
584 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
590 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
591 static char *findBinaryInPath(const char *bin, char *envr)
593 size_t alloc_size = 0;
600 ptr = strchr(start, ':'); /* find next $PATH separator. */
604 size = strlen(start) + strlen(bin) + 2;
605 if (size > alloc_size) {
606 char *x = (char *) realloc(exe, size);
617 /* build full binary path... */
619 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
623 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
624 strcpy(exe, start); /* i'm lazy. piss off. */
628 start = ptr + 1; /* start points to beginning of next element. */
629 } while (ptr != NULL);
634 return(NULL); /* doesn't exist in path. */
635 } /* findBinaryInPath */
638 char *calcBaseDir(const char *argv0)
640 /* If there isn't a path on argv0, then look through the $PATH for it. */
644 if (strchr(argv0, '/')) {
645 retval = strdup(argv0);
647 *((char *) strrchr(retval, '/')) = '\0';
651 envr = getenv("PATH");
657 retval = findBinaryInPath(argv0, envr);
662 static inline void chdirToAppPath(const char *argv0)
664 char *dir = calcBaseDir(argv0);
666 #if (defined(__APPLE__) && defined(__MACH__))
667 // Chop off /Contents/MacOS if it's at the end of the string, so we
668 // land in the base of the app bundle.
669 const size_t len = strlen(dir);
670 const char *bundledirs = "/Contents/MacOS";
671 const size_t bundledirslen = strlen(bundledirs);
672 if (len > bundledirslen) {
673 char *ptr = (dir + len) - bundledirslen;
674 if (strcasecmp(ptr, bundledirs) == 0)
685 int main(int argc, char **argv)
690 // !!! FIXME: we could use a Win32 API for this. --ryan.
692 chdirToAppPath(argv[0]);
701 //ofstream os("error.txt");
703 //ofstream os("log.txt");
709 while (!gDone && !tryquit) {
713 // check windows messages
720 while ( SDL_PollEvent( &e ) ) {
721 if (!sdlEventProc(e)) {
732 // allow game chance to pause
737 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
748 } 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, '.');
788 if (strcasecmp(ptr + 1, "png") == 0)
789 return load_png(file_name, tex);
790 else if (strcasecmp(ptr + 1, "jpg") == 0)
791 return load_jpg(file_name, tex);
794 STUBBED("Unsupported image type");
799 struct my_error_mgr {
800 struct jpeg_error_mgr pub; /* "public" fields */
801 jmp_buf setjmp_buffer; /* for return to caller */
803 typedef struct my_error_mgr * my_error_ptr;
806 static void my_error_exit(j_common_ptr cinfo)
808 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
809 longjmp(err->setjmp_buffer, 1);
812 /* stolen from public domain example.c code in libjpg distribution. */
813 static bool load_jpg(const char *file_name, TGAImageRec &tex)
815 struct jpeg_decompress_struct cinfo;
816 struct my_error_mgr jerr;
817 JSAMPROW buffer[1]; /* Output row buffer */
818 int row_stride; /* physical row width in output buffer */
819 FILE *infile = fopen(file_name, "rb");
824 cinfo.err = jpeg_std_error(&jerr.pub);
825 jerr.pub.error_exit = my_error_exit;
826 if (setjmp(jerr.setjmp_buffer)) {
827 jpeg_destroy_decompress(&cinfo);
832 jpeg_create_decompress(&cinfo);
833 jpeg_stdio_src(&cinfo, infile);
834 (void) jpeg_read_header(&cinfo, TRUE);
836 cinfo.out_color_space = JCS_RGB;
837 cinfo.quantize_colors = 0;
838 (void) jpeg_calc_output_dimensions(&cinfo);
839 (void) jpeg_start_decompress(&cinfo);
841 row_stride = cinfo.output_width * cinfo.output_components;
842 tex.sizeX = cinfo.output_width;
843 tex.sizeY = cinfo.output_height;
846 while (cinfo.output_scanline < cinfo.output_height) {
847 buffer[0] = (JSAMPROW)(char *)tex.data +
848 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
849 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
852 (void) jpeg_finish_decompress(&cinfo);
853 jpeg_destroy_decompress(&cinfo);
860 /* stolen from public domain example.c code in libpng distribution. */
861 static bool load_png(const char *file_name, TGAImageRec &tex)
863 bool hasalpha = false;
864 png_structp png_ptr = NULL;
865 png_infop info_ptr = NULL;
866 png_uint_32 width, height;
867 int bit_depth, color_type, interlace_type;
869 png_byte **row_pointers = NULL;
870 FILE *fp = fopen(file_name, "rb");
873 cerr << file_name << " not found" << endl;
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);
910 png_byte *dst = tex.data;
911 for (int i = height - 1; i >= 0; i--) {
912 png_byte *src = row_pointers[i];
913 for (unsigned j = 0; j < width; j++) {
925 png_byte *dst = tex.data;
926 int pitch = width * 4;
927 for (int i = height - 1; i >= 0; i--, dst += pitch)
928 memcpy(dst, row_pointers[i], pitch);
938 cerr << "There was a problem loading " << file_name << endl;
940 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
947 bool save_image(const char *file_name)
949 const char *ptr = strrchr((char *)file_name, '.');
951 if (strcasecmp(ptr + 1, "png") == 0)
952 return save_png(file_name);
955 STUBBED("Unsupported image type");
960 static bool save_png(const char *file_name)
963 png_structp png_ptr = NULL;
964 png_infop info_ptr = NULL;
967 fp = fopen(file_name, "wb");
971 png_bytep *row_pointers = new png_bytep[kContextHeight];
972 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
973 if ((!screenshot) || (!row_pointers))
977 glReadPixels(0, 0, kContextWidth, kContextHeight,
978 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
979 if (glGetError() != GL_NO_ERROR)
982 for (int i = 0; i < kContextHeight; i++)
983 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
985 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
989 info_ptr = png_create_info_struct(png_ptr);
990 if (info_ptr == NULL)
993 if (setjmp(png_jmpbuf(png_ptr)))
996 png_init_io(png_ptr, fp);
998 if (setjmp(png_jmpbuf(png_ptr)))
1001 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1002 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1003 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1005 png_write_info(png_ptr, info_ptr);
1007 if (setjmp(png_jmpbuf(png_ptr)))
1010 png_write_image(png_ptr, row_pointers);
1012 if (setjmp(png_jmpbuf(png_ptr)))
1015 png_write_end(png_ptr, NULL);
1019 png_destroy_write_struct(&png_ptr, &info_ptr);
1020 delete[] screenshot;
1021 delete[] row_pointers;
1025 unlink(ConvertFileName(file_name));