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);
179 glDisable( GL_LIGHTING);
180 glDisable( GL_LOGIC_OP);
181 glDisable( GL_TEXTURE_1D);
182 glDisable( GL_TEXTURE_2D);
183 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
184 glPixelTransferi( GL_RED_SCALE, 1);
185 glPixelTransferi( GL_RED_BIAS, 0);
186 glPixelTransferi( GL_GREEN_SCALE, 1);
187 glPixelTransferi( GL_GREEN_BIAS, 0);
188 glPixelTransferi( GL_BLUE_SCALE, 1);
189 glPixelTransferi( GL_BLUE_BIAS, 0);
190 glPixelTransferi( GL_ALPHA_SCALE, 1);
191 glPixelTransferi( GL_ALPHA_BIAS, 0);
193 // set initial rendering states
194 glShadeModel( GL_SMOOTH);
196 glDepthFunc( GL_LEQUAL);
197 glDepthMask( GL_TRUE);
198 glEnable( GL_DEPTH_TEST);
199 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
200 glCullFace( GL_FRONT);
201 glEnable( GL_CULL_FACE);
202 glEnable( GL_LIGHTING);
203 glEnable( GL_DITHER);
204 glEnable( GL_COLOR_MATERIAL);
205 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
206 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
207 glAlphaFunc( GL_GREATER, 0.5f);
209 if ( CanInitStereo(stereomode) ) {
210 InitStereo(stereomode);
212 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
213 stereomode = stereoNone;
217 void toggleFullscreen()
219 fullscreen = !fullscreen;
220 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
221 if (flags & SDL_WINDOW_FULLSCREEN) {
222 flags &= ~SDL_WINDOW_FULLSCREEN;
224 flags |= SDL_WINDOW_FULLSCREEN;
226 SDL_SetWindowFullscreen(sdlwindow, flags);
229 static SDL_bool sdlEventProc(const SDL_Event &e)
235 case SDL_WINDOWEVENT:
236 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
241 case SDL_MOUSEMOTION:
242 deltah += e.motion.xrel;
243 deltav += e.motion.yrel;
247 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
248 (e.key.keysym.mod & KMOD_CTRL)) {
249 SDL_bool mode = SDL_TRUE;
250 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
251 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
252 SDL_SetWindowGrab(sdlwindow, mode);
253 SDL_SetRelativeMouseMode(mode);
254 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
264 // --------------------------------------------------------------------------
266 static Point gMidPoint;
280 if (!SDL_WasInit(SDL_INIT_VIDEO))
281 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
282 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
285 if (!LoadSettings()) {
286 fprintf(stderr, "Failed to load config, creating default\n");
289 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
293 if (SDL_GL_LoadLibrary(NULL) == -1) {
294 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
299 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
300 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
301 SDL_DisplayMode mode;
302 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
304 if ((mode.w < 640) || (mode.h < 480))
305 continue; // sane lower limit.
306 pair<int,int> resolution(mode.w, mode.h);
307 resolutions.insert(resolution);
311 if (resolutions.empty()) {
312 const std::string error = "No suitable video resolutions found.";
313 cerr << error << endl;
314 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
319 if (cmdline("showresolutions")) {
320 printf("Available resolutions:\n");
321 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
322 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
326 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
327 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
329 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
330 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
332 sdlflags |= SDL_WINDOW_FULLSCREEN;
334 if (!cmdline("nomousegrab"))
335 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
337 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
338 kContextWidth, kContextHeight, sdlflags);
341 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
342 fprintf(stderr, "forcing 640x480...\n");
344 kContextHeight = 480;
345 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
346 kContextWidth, kContextHeight, sdlflags);
348 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
349 fprintf(stderr, "forcing 640x480 windowed mode...\n");
350 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
351 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
352 kContextWidth, kContextHeight, sdlflags);
355 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
361 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
363 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
368 SDL_GL_MakeCurrent(sdlwindow, glctx);
370 if (!lookup_all_glsyms()) {
371 fprintf(stderr, "Missing required OpenGL functions.\n");
377 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
379 fprintf(stderr, "Failed to get a double-buffered context.\n");
384 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
385 SDL_GL_SetSwapInterval(1);
388 if (!cmdline("nomousegrab"))
389 SDL_SetRelativeMouseMode(SDL_TRUE);
393 GLint width = kContextWidth;
394 GLint height = kContextHeight;
395 gMidPoint.h = width / 2;
396 gMidPoint.v = height / 2;
398 screenheight = height;
401 newscreenwidth = screenwidth;
402 newscreenheight = screenheight;
404 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
405 pair<int,int> startresolution(width,height);
406 if (resolutions.find(startresolution) == resolutions.end()) {
407 resolutions.insert(startresolution);
416 static void DoMouse()
419 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
420 deltah *= usermousesensitivity;
421 deltav *= usermousesensitivity;
422 mousecoordh += deltah;
423 mousecoordv += deltav;
426 else if (mousecoordh >= kContextWidth)
427 mousecoordh = kContextWidth - 1;
430 else if (mousecoordv >= kContextHeight)
431 mousecoordv = kContextHeight - 1;
436 void DoFrameRate (int update)
438 static long frames = 0;
440 static AbsoluteTime time = {0, 0};
441 static AbsoluteTime frametime = {0, 0};
442 AbsoluteTime currTime = UpTime ();
443 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
445 if (0 > deltaTime) // if negative microseconds
446 deltaTime /= -1000000.0;
447 else // else milliseconds
450 multiplier = deltaTime;
451 if (multiplier < .001)
456 frametime = currTime; // reset for next time interval
458 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
460 if (0 > deltaTime) // if negative microseconds
461 deltaTime /= -1000000.0;
462 else // else milliseconds
465 if (0.001 <= deltaTime) { // has update interval passed
467 time = currTime; // reset for next time interval
476 static float sps = 200;
478 static float oldmult;
484 fps = 1 / multiplier;
486 count = multiplier * sps;
490 realmultiplier = multiplier;
491 multiplier *= gamespeed;
498 multiplier *= .00001;
499 if (slomo && !mainmenu)
500 multiplier *= slomospeed;
501 oldmult = multiplier;
502 multiplier /= (float)count;
508 for (int i = 0; i < count; i++) {
511 multiplier = oldmult;
514 /* - Debug code to test how many channels were active on average per frame
515 static long frames = 0;
517 static AbsoluteTime start = {0,0};
518 AbsoluteTime currTime = UpTime ();
519 static int num_channels = 0;
521 num_channels += OPENAL_GetChannelsPlaying();
522 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
524 if (0 > deltaTime) // if negative microseconds
525 deltaTime /= -1000000.0;
526 else // else milliseconds
534 float avg_channels = (float)num_channels / (float)frames;
536 ofstream opstream("log.txt",ios::app);
537 opstream << "Average frame count: ";
539 opstream << " frames - ";
540 opstream << avg_channels;
541 opstream << " per frame.\n";
548 if ( stereomode == stereoNone ) {
549 DrawGLScene(stereoCenter);
551 DrawGLScene(stereoLeft);
552 DrawGLScene(stereoRight);
556 // --------------------------------------------------------------------------
564 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
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;
571 #endif // __MINGW32__
575 // --------------------------------------------------------------------------
577 static bool IsFocused()
579 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
585 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
586 static char *findBinaryInPath(const char *bin, char *envr)
588 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) {
601 char *x = (char *) realloc(exe, size);
612 /* build full binary path... */
614 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
618 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
619 strcpy(exe, start); /* i'm lazy. piss off. */
623 start = ptr + 1; /* start points to beginning of next element. */
624 } while (ptr != NULL);
629 return(NULL); /* doesn't exist in path. */
630 } /* findBinaryInPath */
633 char *calcBaseDir(const char *argv0)
635 /* If there isn't a path on argv0, then look through the $PATH for it. */
639 if (strchr(argv0, '/')) {
640 retval = strdup(argv0);
642 *((char *) strrchr(retval, '/')) = '\0';
646 envr = getenv("PATH");
652 retval = findBinaryInPath(argv0, envr);
657 static inline void chdirToAppPath(const char *argv0)
659 char *dir = calcBaseDir(argv0);
661 #if (defined(__APPLE__) && defined(__MACH__))
662 // Chop off /Contents/MacOS if it's at the end of the string, so we
663 // land in the base of the app bundle.
664 const size_t len = strlen(dir);
665 const char *bundledirs = "/Contents/MacOS";
666 const size_t bundledirslen = strlen(bundledirs);
667 if (len > bundledirslen) {
668 char *ptr = (dir + len) - bundledirslen;
669 if (strcasecmp(ptr, bundledirs) == 0)
680 int main(int argc, char **argv)
685 // !!! FIXME: we could use a Win32 API for this. --ryan.
687 chdirToAppPath(argv[0]);
696 //ofstream os("error.txt");
698 //ofstream os("log.txt");
704 while (!gDone && !tryquit) {
708 // check windows messages
715 while ( SDL_PollEvent( &e ) ) {
716 if (!sdlEventProc(e)) {
727 // allow game chance to pause
732 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
743 } catch (const std::exception& error) {
746 std::string e = "Caught exception: ";
751 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
761 // --------------------------------------------------------------------------
764 bool LoadImage(const char * fname, TGAImageRec & tex)
766 if ( tex.data == NULL )
769 return load_image(fname, tex);
772 static bool load_image(const char *file_name, TGAImageRec &tex)
774 const char *ptr = strrchr((char *)file_name, '.');
776 if (strcasecmp(ptr + 1, "png") == 0)
777 return load_png(file_name, tex);
778 else if (strcasecmp(ptr + 1, "jpg") == 0)
779 return load_jpg(file_name, tex);
782 STUBBED("Unsupported image type");
787 struct my_error_mgr {
788 struct jpeg_error_mgr pub; /* "public" fields */
789 jmp_buf setjmp_buffer; /* for return to caller */
791 typedef struct my_error_mgr * my_error_ptr;
794 static void my_error_exit(j_common_ptr cinfo)
796 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
797 longjmp(err->setjmp_buffer, 1);
800 /* stolen from public domain example.c code in libjpg distribution. */
801 static bool load_jpg(const char *file_name, TGAImageRec &tex)
803 struct jpeg_decompress_struct cinfo;
804 struct my_error_mgr jerr;
805 JSAMPROW buffer[1]; /* Output row buffer */
806 int row_stride; /* physical row width in output buffer */
807 FILE *infile = fopen(file_name, "rb");
812 cinfo.err = jpeg_std_error(&jerr.pub);
813 jerr.pub.error_exit = my_error_exit;
814 if (setjmp(jerr.setjmp_buffer)) {
815 jpeg_destroy_decompress(&cinfo);
820 jpeg_create_decompress(&cinfo);
821 jpeg_stdio_src(&cinfo, infile);
822 (void) jpeg_read_header(&cinfo, TRUE);
824 cinfo.out_color_space = JCS_RGB;
825 cinfo.quantize_colors = 0;
826 (void) jpeg_calc_output_dimensions(&cinfo);
827 (void) jpeg_start_decompress(&cinfo);
829 row_stride = cinfo.output_width * cinfo.output_components;
830 tex.sizeX = cinfo.output_width;
831 tex.sizeY = cinfo.output_height;
834 while (cinfo.output_scanline < cinfo.output_height) {
835 buffer[0] = (JSAMPROW)(char *)tex.data +
836 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
837 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
840 (void) jpeg_finish_decompress(&cinfo);
841 jpeg_destroy_decompress(&cinfo);
848 /* stolen from public domain example.c code in libpng distribution. */
849 static bool load_png(const char *file_name, TGAImageRec &tex)
851 bool hasalpha = false;
852 png_structp png_ptr = NULL;
853 png_infop info_ptr = NULL;
854 png_uint_32 width, height;
855 int bit_depth, color_type, interlace_type;
857 png_byte **row_pointers = NULL;
858 FILE *fp = fopen(file_name, "rb");
861 cerr << file_name << " not found" << endl;
865 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
869 info_ptr = png_create_info_struct(png_ptr);
870 if (info_ptr == NULL)
873 if (setjmp(png_jmpbuf(png_ptr)))
876 png_init_io(png_ptr, fp);
877 png_read_png(png_ptr, info_ptr,
878 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
880 png_get_IHDR(png_ptr, info_ptr, &width, &height,
881 &bit_depth, &color_type, &interlace_type, NULL, NULL);
883 if (bit_depth != 8) // transform SHOULD handle this...
886 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
889 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
892 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
893 row_pointers = png_get_rows(png_ptr, info_ptr);
898 png_byte *dst = tex.data;
899 for (int i = height - 1; i >= 0; i--) {
900 png_byte *src = row_pointers[i];
901 for (unsigned j = 0; j < width; j++) {
913 png_byte *dst = tex.data;
914 int pitch = width * 4;
915 for (int i = height - 1; i >= 0; i--, dst += pitch)
916 memcpy(dst, row_pointers[i], pitch);
926 cerr << "There was a problem loading " << file_name << endl;
928 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
935 bool save_image(const char *file_name)
937 const char *ptr = strrchr((char *)file_name, '.');
939 if (strcasecmp(ptr + 1, "png") == 0)
940 return save_png(file_name);
943 STUBBED("Unsupported image type");
948 static bool save_png(const char *file_name)
951 png_structp png_ptr = NULL;
952 png_infop info_ptr = NULL;
955 fp = fopen(file_name, "wb");
959 png_bytep *row_pointers = new png_bytep[kContextHeight];
960 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
961 if ((!screenshot) || (!row_pointers))
965 glReadPixels(0, 0, kContextWidth, kContextHeight,
966 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
967 if (glGetError() != GL_NO_ERROR)
970 for (int i = 0; i < kContextHeight; i++)
971 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
973 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
977 info_ptr = png_create_info_struct(png_ptr);
978 if (info_ptr == NULL)
981 if (setjmp(png_jmpbuf(png_ptr)))
984 png_init_io(png_ptr, fp);
986 if (setjmp(png_jmpbuf(png_ptr)))
989 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
990 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
991 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
993 png_write_info(png_ptr, info_ptr);
995 if (setjmp(png_jmpbuf(png_ptr)))
998 png_write_image(png_ptr, row_pointers);
1000 if (setjmp(png_jmpbuf(png_ptr)))
1003 png_write_end(png_ptr, NULL);
1007 png_destroy_write_struct(&png_ptr, &info_ptr);
1008 delete[] screenshot;
1009 delete[] row_pointers;
1013 unlink(ConvertFileName(file_name));