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 modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 Lugaru 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. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
33 static bool load_image(const char * fname, TGAImageRec & tex);
34 static bool load_png(const char * fname, TGAImageRec & tex);
35 static bool load_jpg(const char * fname, TGAImageRec & tex);
36 bool save_image(const char * fname);
37 static bool save_png(const char * fname);
40 #include "openal_wrapper.h"
42 extern float multiplier;
44 extern float realmultiplier;
46 extern bool cellophane;
47 extern float texdetail;
51 extern bool stillloading;
56 extern float slomospeed;
57 extern float slomofreq;
68 #include "MacCompatibility.h"
73 #include "win-res/resource.h"
76 extern SDL_Window *sdlwindow;
80 set<pair<int,int>> resolutions;
87 // statics/globals (internal only) ------------------------------------------
91 #pragma warning(disable: 4273)
94 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
95 #define GL_FUNC(ret,fn,params,call,rt) \
97 static ret (GLAPIENTRY *p##fn) params = NULL; \
98 ret GLAPIENTRY fn params { rt p##fn call; } \
102 #endif // __MINGW32__
108 static bool lookup_glsym(const char *funcname, void **func)
110 *func = SDL_GL_GetProcAddress(funcname);
112 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
118 static bool lookup_all_glsyms(void)
121 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
122 #define GL_FUNC(ret,fn,params,call,rt) \
123 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
126 #endif // __MINGW32__
130 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
131 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
135 #endif // __MINGW32__
140 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
147 Boolean gDone = false;
149 static int _argc = 0;
150 static char **_argv = NULL;
152 bool cmdline(const char *cmd)
154 for (int i = 1; i < _argc; i++) {
155 char *arg = _argv[i];
158 if (strcasecmp(arg, cmd) == 0)
165 //-----------------------------------------------------------------------------------------------------------------------
171 glClear( GL_COLOR_BUFFER_BIT );
175 glDisable( GL_ALPHA_TEST);
176 glDisable( GL_BLEND);
177 glDisable( GL_DEPTH_TEST);
178 //glDisable( GL_DITHER);
180 glDisable( GL_LIGHTING);
181 glDisable( GL_LOGIC_OP);
182 glDisable( GL_TEXTURE_1D);
183 glDisable( GL_TEXTURE_2D);
184 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
185 glPixelTransferi( GL_RED_SCALE, 1);
186 glPixelTransferi( GL_RED_BIAS, 0);
187 glPixelTransferi( GL_GREEN_SCALE, 1);
188 glPixelTransferi( GL_GREEN_BIAS, 0);
189 glPixelTransferi( GL_BLUE_SCALE, 1);
190 glPixelTransferi( GL_BLUE_BIAS, 0);
191 glPixelTransferi( GL_ALPHA_SCALE, 1);
192 glPixelTransferi( GL_ALPHA_BIAS, 0);
194 // set initial rendering states
195 glShadeModel( GL_SMOOTH);
197 glDepthFunc( GL_LEQUAL);
198 glDepthMask( GL_TRUE);
199 //glDepthRange( FRONT_CLIP, BACK_CLIP);
200 glEnable( GL_DEPTH_TEST);
201 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
202 glCullFace( GL_FRONT);
203 glEnable( GL_CULL_FACE);
204 glEnable( GL_LIGHTING);
205 //glEnable( GL_LIGHT_MODEL_AMBIENT);
206 glEnable( GL_DITHER);
207 glEnable( GL_COLOR_MATERIAL);
208 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
209 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
210 glAlphaFunc( GL_GREATER, 0.5f);
212 if ( CanInitStereo(stereomode) ) {
213 InitStereo(stereomode);
215 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
216 stereomode = stereoNone;
220 void toggleFullscreen()
222 fullscreen = !fullscreen;
223 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
224 if (flags & SDL_WINDOW_FULLSCREEN) {
225 flags &= ~SDL_WINDOW_FULLSCREEN;
227 flags |= SDL_WINDOW_FULLSCREEN;
229 SDL_SetWindowFullscreen(sdlwindow, flags);
232 static SDL_bool sdlEventProc(const SDL_Event &e)
238 case SDL_WINDOWEVENT:
239 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
244 case SDL_MOUSEMOTION:
245 deltah += e.motion.xrel;
246 deltav += e.motion.yrel;
250 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
251 (e.key.keysym.mod & KMOD_CTRL)) {
252 SDL_bool mode = SDL_TRUE;
253 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
254 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
255 SDL_SetWindowGrab(sdlwindow, mode);
256 SDL_SetRelativeMouseMode(mode);
257 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
267 // --------------------------------------------------------------------------
269 static Point gMidPoint;
283 if (!SDL_WasInit(SDL_INIT_VIDEO))
284 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
285 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
288 if (!LoadSettings()) {
289 fprintf(stderr, "Failed to load config, creating default\n");
292 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
296 if (SDL_GL_LoadLibrary(NULL) == -1) {
297 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
302 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
303 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
304 SDL_DisplayMode mode;
305 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
307 if ((mode.w < 640) || (mode.h < 480))
308 continue; // sane lower limit.
309 pair<int,int> resolution(mode.w, mode.h);
310 resolutions.insert(resolution);
314 if (resolutions.empty()) {
315 const std::string error = "No suitable video resolutions found.";
316 cerr << error << endl;
317 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
322 if (cmdline("showresolutions")) {
323 printf("Available resolutions:\n");
324 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
325 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
329 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
330 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
332 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
333 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
335 sdlflags |= SDL_WINDOW_FULLSCREEN;
337 if (!cmdline("nomousegrab"))
338 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
340 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
341 kContextWidth, kContextHeight, sdlflags);
344 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
345 fprintf(stderr, "forcing 640x480...\n");
347 kContextHeight = 480;
348 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
349 kContextWidth, kContextHeight, sdlflags);
351 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
352 fprintf(stderr, "forcing 640x480 windowed mode...\n");
353 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
354 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
355 kContextWidth, kContextHeight, sdlflags);
358 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
364 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
366 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
371 SDL_GL_MakeCurrent(sdlwindow, glctx);
373 if (!lookup_all_glsyms()) {
374 fprintf(stderr, "Missing required OpenGL functions.\n");
380 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
382 fprintf(stderr, "Failed to get a double-buffered context.\n");
387 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
388 SDL_GL_SetSwapInterval(1);
391 if (!cmdline("nomousegrab"))
392 SDL_SetRelativeMouseMode(SDL_TRUE);
396 GLint width = kContextWidth;
397 GLint height = kContextHeight;
398 gMidPoint.h = width / 2;
399 gMidPoint.v = height / 2;
401 screenheight = height;
404 newscreenwidth = screenwidth;
405 newscreenheight = screenheight;
407 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
408 pair<int,int> startresolution(width,height);
409 if (resolutions.find(startresolution) == resolutions.end()) {
410 resolutions.insert(startresolution);
419 static void DoMouse()
422 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
423 deltah *= usermousesensitivity;
424 deltav *= usermousesensitivity;
425 mousecoordh += deltah;
426 mousecoordv += deltav;
429 else if (mousecoordh >= kContextWidth)
430 mousecoordh = kContextWidth - 1;
433 else if (mousecoordv >= kContextHeight)
434 mousecoordv = kContextHeight - 1;
439 void DoFrameRate (int update)
441 static long frames = 0;
443 static AbsoluteTime time = {0, 0};
444 static AbsoluteTime frametime = {0, 0};
445 AbsoluteTime currTime = UpTime ();
446 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
448 if (0 > deltaTime) // if negative microseconds
449 deltaTime /= -1000000.0;
450 else // else milliseconds
453 multiplier = deltaTime;
454 if (multiplier < .001)
459 frametime = currTime; // reset for next time interval
461 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
463 if (0 > deltaTime) // if negative microseconds
464 deltaTime /= -1000000.0;
465 else // else milliseconds
468 if (0.001 <= deltaTime) { // has update interval passed
470 time = currTime; // reset for next time interval
479 static float sps = 200;
481 static float oldmult;
487 fps = 1 / multiplier;
489 count = multiplier * sps;
493 realmultiplier = multiplier;
494 multiplier *= gamespeed;
501 multiplier *= .00001;
502 if (slomo && !mainmenu)
503 multiplier *= slomospeed;
504 oldmult = multiplier;
505 multiplier /= (float)count;
511 for (int i = 0; i < count; i++) {
514 multiplier = oldmult;
517 /* - Debug code to test how many channels were active on average per frame
518 static long frames = 0;
520 static AbsoluteTime start = {0,0};
521 AbsoluteTime currTime = UpTime ();
522 static int num_channels = 0;
524 num_channels += OPENAL_GetChannelsPlaying();
525 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
527 if (0 > deltaTime) // if negative microseconds
528 deltaTime /= -1000000.0;
529 else // else milliseconds
537 float avg_channels = (float)num_channels / (float)frames;
539 ofstream opstream("log.txt",ios::app);
540 opstream << "Average frame count: ";
542 opstream << " frames - ";
543 opstream << avg_channels;
544 opstream << " per frame.\n";
551 if ( stereomode == stereoNone ) {
552 DrawGLScene(stereoCenter);
554 DrawGLScene(stereoLeft);
555 DrawGLScene(stereoRight);
559 // --------------------------------------------------------------------------
567 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
568 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
571 // cheat here...static destructors are calling glDeleteTexture() after
572 // the context is destroyed and libGL unloaded by SDL_Quit().
573 pglDeleteTextures = glDeleteTextures_doNothing;
574 #endif // __MINGW32__
578 // --------------------------------------------------------------------------
580 static bool IsFocused()
582 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
588 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
589 static char *findBinaryInPath(const char *bin, char *envr)
591 size_t alloc_size = 0;
598 ptr = strchr(start, ':'); /* find next $PATH separator. */
602 size = strlen(start) + strlen(bin) + 2;
603 if (size > alloc_size) {
604 char *x = (char *) realloc(exe, size);
615 /* build full binary path... */
617 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
621 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 if (strchr(argv0, '/')) {
643 retval = strdup(argv0);
645 *((char *) strrchr(retval, '/')) = '\0';
649 envr = getenv("PATH");
655 retval = findBinaryInPath(argv0, envr);
660 static inline void chdirToAppPath(const char *argv0)
662 char *dir = calcBaseDir(argv0);
664 #if (defined(__APPLE__) && defined(__MACH__))
665 // Chop off /Contents/MacOS if it's at the end of the string, so we
666 // land in the base of the app bundle.
667 const size_t len = strlen(dir);
668 const char *bundledirs = "/Contents/MacOS";
669 const size_t bundledirslen = strlen(bundledirs);
670 if (len > bundledirslen) {
671 char *ptr = (dir + len) - bundledirslen;
672 if (strcasecmp(ptr, bundledirs) == 0)
683 int main(int argc, char **argv)
688 // !!! FIXME: we could use a Win32 API for this. --ryan.
690 chdirToAppPath(argv[0]);
699 //ofstream os("error.txt");
701 //ofstream os("log.txt");
707 while (!gDone && !tryquit) {
711 // check windows messages
718 while ( SDL_PollEvent( &e ) ) {
719 if (!sdlEventProc(e)) {
730 // allow game chance to pause
735 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
746 } catch (const std::exception& error) {
749 std::string e = "Caught exception: ";
754 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
764 // --------------------------------------------------------------------------
767 bool LoadImage(const char * fname, TGAImageRec & tex)
769 if ( tex.data == NULL )
772 return load_image(fname, tex);
775 void ScreenShot(const char * fname)
782 static bool load_image(const char *file_name, TGAImageRec &tex)
784 const char *ptr = strrchr((char *)file_name, '.');
786 if (strcasecmp(ptr + 1, "png") == 0)
787 return load_png(file_name, tex);
788 else if (strcasecmp(ptr + 1, "jpg") == 0)
789 return load_jpg(file_name, tex);
792 STUBBED("Unsupported image type");
797 struct my_error_mgr {
798 struct jpeg_error_mgr pub; /* "public" fields */
799 jmp_buf setjmp_buffer; /* for return to caller */
801 typedef struct my_error_mgr * my_error_ptr;
804 static void my_error_exit(j_common_ptr cinfo)
806 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
807 longjmp(err->setjmp_buffer, 1);
810 /* stolen from public domain example.c code in libjpg distribution. */
811 static bool load_jpg(const char *file_name, TGAImageRec &tex)
813 struct jpeg_decompress_struct cinfo;
814 struct my_error_mgr jerr;
815 JSAMPROW buffer[1]; /* Output row buffer */
816 int row_stride; /* physical row width in output buffer */
817 FILE *infile = fopen(file_name, "rb");
822 cinfo.err = jpeg_std_error(&jerr.pub);
823 jerr.pub.error_exit = my_error_exit;
824 if (setjmp(jerr.setjmp_buffer)) {
825 jpeg_destroy_decompress(&cinfo);
830 jpeg_create_decompress(&cinfo);
831 jpeg_stdio_src(&cinfo, infile);
832 (void) jpeg_read_header(&cinfo, TRUE);
834 cinfo.out_color_space = JCS_RGB;
835 cinfo.quantize_colors = 0;
836 (void) jpeg_calc_output_dimensions(&cinfo);
837 (void) jpeg_start_decompress(&cinfo);
839 row_stride = cinfo.output_width * cinfo.output_components;
840 tex.sizeX = cinfo.output_width;
841 tex.sizeY = cinfo.output_height;
844 while (cinfo.output_scanline < cinfo.output_height) {
845 buffer[0] = (JSAMPROW)(char *)tex.data +
846 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
847 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
850 (void) jpeg_finish_decompress(&cinfo);
851 jpeg_destroy_decompress(&cinfo);
858 /* stolen from public domain example.c code in libpng distribution. */
859 static bool load_png(const char *file_name, TGAImageRec &tex)
861 bool hasalpha = false;
862 png_structp png_ptr = NULL;
863 png_infop info_ptr = NULL;
864 png_uint_32 width, height;
865 int bit_depth, color_type, interlace_type;
867 png_byte **row_pointers = NULL;
868 FILE *fp = fopen(file_name, "rb");
871 cerr << file_name << " not found" << endl;
875 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
879 info_ptr = png_create_info_struct(png_ptr);
880 if (info_ptr == NULL)
883 if (setjmp(png_jmpbuf(png_ptr)))
886 png_init_io(png_ptr, fp);
887 png_read_png(png_ptr, info_ptr,
888 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
890 png_get_IHDR(png_ptr, info_ptr, &width, &height,
891 &bit_depth, &color_type, &interlace_type, NULL, NULL);
893 if (bit_depth != 8) // transform SHOULD handle this...
896 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
899 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
902 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
903 row_pointers = png_get_rows(png_ptr, info_ptr);
908 png_byte *dst = tex.data;
909 for (int i = height - 1; i >= 0; i--) {
910 png_byte *src = row_pointers[i];
911 for (unsigned 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);
936 cerr << "There was a problem loading " << file_name << endl;
938 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
945 bool save_image(const char *file_name)
947 const char *ptr = strrchr((char *)file_name, '.');
949 if (strcasecmp(ptr + 1, "png") == 0)
950 return save_png(file_name);
953 STUBBED("Unsupported image type");
958 static bool save_png(const char *file_name)
961 png_structp png_ptr = NULL;
962 png_infop info_ptr = NULL;
965 fp = fopen(file_name, "wb");
969 png_bytep *row_pointers = new png_bytep[kContextHeight];
970 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
971 if ((!screenshot) || (!row_pointers))
975 glReadPixels(0, 0, kContextWidth, kContextHeight,
976 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
977 if (glGetError() != GL_NO_ERROR)
980 for (int i = 0; i < kContextHeight; i++)
981 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
983 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
987 info_ptr = png_create_info_struct(png_ptr);
988 if (info_ptr == NULL)
991 if (setjmp(png_jmpbuf(png_ptr)))
994 png_init_io(png_ptr, fp);
996 if (setjmp(png_jmpbuf(png_ptr)))
999 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1000 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1001 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1003 png_write_info(png_ptr, info_ptr);
1005 if (setjmp(png_jmpbuf(png_ptr)))
1008 png_write_image(png_ptr, row_pointers);
1010 if (setjmp(png_jmpbuf(png_ptr)))
1013 png_write_end(png_ptr, NULL);
1017 png_destroy_write_struct(&png_ptr, &info_ptr);
1018 delete[] screenshot;
1019 delete[] row_pointers;
1023 unlink(ConvertFileName(file_name));