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 bool load_image(const char * fname, ImageRec & tex);
34 static bool load_png(const char * fname, ImageRec & tex);
35 static bool load_jpg(const char * fname, ImageRec & 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;
58 extern bool visibleloading;
69 #include "MacCompatibility.h"
74 #include "win-res/resource.h"
77 extern SDL_Window *sdlwindow;
81 set<pair<int,int>> resolutions;
88 // statics/globals (internal only) ------------------------------------------
92 #pragma warning(disable: 4273)
95 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
96 #define GL_FUNC(ret,fn,params,call,rt) \
98 static ret (GLAPIENTRY *p##fn) params = NULL; \
99 ret GLAPIENTRY fn params { rt p##fn call; } \
103 #endif // __MINGW32__
109 static bool lookup_glsym(const char *funcname, void **func)
111 *func = SDL_GL_GetProcAddress(funcname);
113 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
119 static bool lookup_all_glsyms(void)
122 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
123 #define GL_FUNC(ret,fn,params,call,rt) \
124 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
127 #endif // __MINGW32__
131 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
132 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
136 #endif // __MINGW32__
141 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
148 Boolean gDone = false;
150 static int _argc = 0;
151 static char **_argv = NULL;
153 bool cmdline(const char *cmd)
155 for (int i = 1; i < _argc; i++) {
156 char *arg = _argv[i];
159 if (strcasecmp(arg, cmd) == 0)
166 //-----------------------------------------------------------------------------------------------------------------------
172 glClear( GL_COLOR_BUFFER_BIT );
176 glDisable( GL_ALPHA_TEST);
177 glDisable( GL_BLEND);
178 glDisable( GL_DEPTH_TEST);
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 glEnable( GL_DEPTH_TEST);
200 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
201 glCullFace( GL_FRONT);
202 glEnable( GL_CULL_FACE);
203 glEnable( GL_LIGHTING);
204 glEnable( GL_DITHER);
205 glEnable( GL_COLOR_MATERIAL);
206 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
207 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
208 glAlphaFunc( GL_GREATER, 0.5f);
210 if ( CanInitStereo(stereomode) ) {
211 InitStereo(stereomode);
213 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
214 stereomode = stereoNone;
218 void toggleFullscreen()
220 fullscreen = !fullscreen;
221 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
222 if (flags & SDL_WINDOW_FULLSCREEN) {
223 flags &= ~SDL_WINDOW_FULLSCREEN;
225 flags |= SDL_WINDOW_FULLSCREEN;
227 SDL_SetWindowFullscreen(sdlwindow, flags);
230 static SDL_bool sdlEventProc(const SDL_Event &e)
236 case SDL_WINDOWEVENT:
237 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
242 case SDL_MOUSEMOTION:
243 deltah += e.motion.xrel;
244 deltav += e.motion.yrel;
248 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
249 (e.key.keysym.mod & KMOD_CTRL)) {
250 SDL_bool mode = SDL_TRUE;
251 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
252 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
253 SDL_SetWindowGrab(sdlwindow, mode);
254 SDL_SetRelativeMouseMode(mode);
255 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
265 // --------------------------------------------------------------------------
267 static Point gMidPoint;
281 if (!SDL_WasInit(SDL_INIT_VIDEO))
282 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
283 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
286 if (!LoadSettings()) {
287 fprintf(stderr, "Failed to load config, creating default\n");
290 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
294 if (SDL_GL_LoadLibrary(NULL) == -1) {
295 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
300 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
301 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
302 SDL_DisplayMode mode;
303 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
305 if ((mode.w < 640) || (mode.h < 480))
306 continue; // sane lower limit.
307 pair<int,int> resolution(mode.w, mode.h);
308 resolutions.insert(resolution);
312 if (resolutions.empty()) {
313 const std::string error = "No suitable video resolutions found.";
314 cerr << error << endl;
315 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
320 if (cmdline("showresolutions")) {
321 printf("Available resolutions:\n");
322 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
323 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
327 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
328 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
330 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
331 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
333 sdlflags |= SDL_WINDOW_FULLSCREEN;
335 if (!cmdline("nomousegrab"))
336 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
338 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
339 kContextWidth, kContextHeight, sdlflags);
342 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
343 fprintf(stderr, "forcing 640x480...\n");
345 kContextHeight = 480;
346 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
347 kContextWidth, kContextHeight, sdlflags);
349 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
350 fprintf(stderr, "forcing 640x480 windowed mode...\n");
351 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
352 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
353 kContextWidth, kContextHeight, sdlflags);
356 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
362 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
364 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
369 SDL_GL_MakeCurrent(sdlwindow, glctx);
371 if (!lookup_all_glsyms()) {
372 fprintf(stderr, "Missing required OpenGL functions.\n");
378 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
380 fprintf(stderr, "Failed to get a double-buffered context.\n");
385 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
386 SDL_GL_SetSwapInterval(1);
389 if (!cmdline("nomousegrab"))
390 SDL_SetRelativeMouseMode(SDL_TRUE);
394 GLint width = kContextWidth;
395 GLint height = kContextHeight;
396 gMidPoint.h = width / 2;
397 gMidPoint.v = height / 2;
399 screenheight = height;
402 newscreenwidth = screenwidth;
403 newscreenheight = screenheight;
405 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
406 pair<int,int> startresolution(width,height);
407 if (resolutions.find(startresolution) == resolutions.end()) {
408 resolutions.insert(startresolution);
417 static void DoMouse()
420 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
421 deltah *= usermousesensitivity;
422 deltav *= usermousesensitivity;
423 mousecoordh += deltah;
424 mousecoordv += deltav;
427 else if (mousecoordh >= kContextWidth)
428 mousecoordh = kContextWidth - 1;
431 else if (mousecoordv >= kContextHeight)
432 mousecoordv = kContextHeight - 1;
437 void DoFrameRate (int update)
439 static long frames = 0;
441 static AbsoluteTime time = {0, 0};
442 static AbsoluteTime frametime = {0, 0};
443 AbsoluteTime currTime = UpTime ();
444 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
446 if (0 > deltaTime) // if negative microseconds
447 deltaTime /= -1000000.0;
448 else // else milliseconds
451 multiplier = deltaTime;
452 if (multiplier < .001)
457 frametime = currTime; // reset for next time interval
459 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
461 if (0 > deltaTime) // if negative microseconds
462 deltaTime /= -1000000.0;
463 else // else milliseconds
466 if (0.001 <= deltaTime) { // has update interval passed
468 time = currTime; // reset for next time interval
477 static float sps = 200;
479 static float oldmult;
485 fps = 1 / multiplier;
487 count = multiplier * sps;
491 realmultiplier = multiplier;
492 multiplier *= gamespeed;
499 multiplier *= .00001;
500 if (slomo && !mainmenu)
501 multiplier *= slomospeed;
502 oldmult = multiplier;
503 multiplier /= (float)count;
509 for (int i = 0; i < count; i++) {
512 multiplier = oldmult;
515 /* - Debug code to test how many channels were active on average per frame
516 static long frames = 0;
518 static AbsoluteTime start = {0,0};
519 AbsoluteTime currTime = UpTime ();
520 static int num_channels = 0;
522 num_channels += OPENAL_GetChannelsPlaying();
523 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
525 if (0 > deltaTime) // if negative microseconds
526 deltaTime /= -1000000.0;
527 else // else milliseconds
535 float avg_channels = (float)num_channels / (float)frames;
537 ofstream opstream("log.txt",ios::app);
538 opstream << "Average frame count: ";
540 opstream << " frames - ";
541 opstream << avg_channels;
542 opstream << " per frame.\n";
549 if ( stereomode == stereoNone ) {
550 DrawGLScene(stereoCenter);
552 DrawGLScene(stereoLeft);
553 DrawGLScene(stereoRight);
557 // --------------------------------------------------------------------------
565 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
566 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
569 // cheat here...static destructors are calling glDeleteTexture() after
570 // the context is destroyed and libGL unloaded by SDL_Quit().
571 pglDeleteTextures = glDeleteTextures_doNothing;
572 #endif // __MINGW32__
576 // --------------------------------------------------------------------------
578 static bool IsFocused()
580 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
586 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
587 static char *findBinaryInPath(const char *bin, char *envr)
589 size_t alloc_size = 0;
596 ptr = strchr(start, ':'); /* find next $PATH separator. */
600 size = strlen(start) + strlen(bin) + 2;
601 if (size > alloc_size) {
602 char *x = (char *) realloc(exe, size);
613 /* build full binary path... */
615 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
619 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
620 strcpy(exe, start); /* i'm lazy. piss off. */
624 start = ptr + 1; /* start points to beginning of next element. */
625 } while (ptr != NULL);
630 return(NULL); /* doesn't exist in path. */
631 } /* findBinaryInPath */
634 char *calcBaseDir(const char *argv0)
636 /* If there isn't a path on argv0, then look through the $PATH for it. */
640 if (strchr(argv0, '/')) {
641 retval = strdup(argv0);
643 *((char *) strrchr(retval, '/')) = '\0';
647 envr = getenv("PATH");
653 retval = findBinaryInPath(argv0, envr);
658 static inline void chdirToAppPath(const char *argv0)
660 char *dir = calcBaseDir(argv0);
662 #if (defined(__APPLE__) && defined(__MACH__))
663 // Chop off /Contents/MacOS if it's at the end of the string, so we
664 // land in the base of the app bundle.
665 const size_t len = strlen(dir);
666 const char *bundledirs = "/Contents/MacOS";
667 const size_t bundledirslen = strlen(bundledirs);
668 if (len > bundledirslen) {
669 char *ptr = (dir + len) - bundledirslen;
670 if (strcasecmp(ptr, bundledirs) == 0)
681 int main(int argc, char **argv)
686 // !!! FIXME: we could use a Win32 API for this. --ryan.
688 chdirToAppPath(argv[0]);
697 //ofstream os("error.txt");
699 //ofstream os("log.txt");
705 while (!gDone && !tryquit) {
709 // check windows messages
716 while ( SDL_PollEvent( &e ) ) {
717 if (!sdlEventProc(e)) {
728 // allow game chance to pause
733 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
744 } catch (const std::exception& error) {
747 std::string e = "Caught exception: ";
752 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
762 // --------------------------------------------------------------------------
764 bool load_image(const char *file_name, ImageRec &tex)
767 Game::LoadingScreen();
769 if ( tex.data == NULL )
772 const char *ptr = strrchr((char *)file_name, '.');
774 if (strcasecmp(ptr + 1, "png") == 0)
775 return load_png(file_name, tex);
776 else if (strcasecmp(ptr + 1, "jpg") == 0)
777 return load_jpg(file_name, tex);
780 STUBBED("Unsupported image type");
784 struct my_error_mgr {
785 struct jpeg_error_mgr pub; /* "public" fields */
786 jmp_buf setjmp_buffer; /* for return to caller */
788 typedef struct my_error_mgr * my_error_ptr;
791 static void my_error_exit(j_common_ptr cinfo)
793 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
794 longjmp(err->setjmp_buffer, 1);
797 /* stolen from public domain example.c code in libjpg distribution. */
798 static bool load_jpg(const char *file_name, ImageRec &tex)
800 struct jpeg_decompress_struct cinfo;
801 struct my_error_mgr jerr;
802 JSAMPROW buffer[1]; /* Output row buffer */
803 int row_stride; /* physical row width in output buffer */
804 FILE *infile = fopen(file_name, "rb");
809 cinfo.err = jpeg_std_error(&jerr.pub);
810 jerr.pub.error_exit = my_error_exit;
811 if (setjmp(jerr.setjmp_buffer)) {
812 jpeg_destroy_decompress(&cinfo);
817 jpeg_create_decompress(&cinfo);
818 jpeg_stdio_src(&cinfo, infile);
819 (void) jpeg_read_header(&cinfo, TRUE);
821 cinfo.out_color_space = JCS_RGB;
822 cinfo.quantize_colors = 0;
823 (void) jpeg_calc_output_dimensions(&cinfo);
824 (void) jpeg_start_decompress(&cinfo);
826 row_stride = cinfo.output_width * cinfo.output_components;
827 tex.sizeX = cinfo.output_width;
828 tex.sizeY = cinfo.output_height;
831 while (cinfo.output_scanline < cinfo.output_height) {
832 buffer[0] = (JSAMPROW)(char *)tex.data +
833 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
834 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
837 (void) jpeg_finish_decompress(&cinfo);
838 jpeg_destroy_decompress(&cinfo);
845 /* stolen from public domain example.c code in libpng distribution. */
846 static bool load_png(const char *file_name, ImageRec &tex)
848 bool hasalpha = false;
849 png_structp png_ptr = NULL;
850 png_infop info_ptr = NULL;
851 png_uint_32 width, height;
852 int bit_depth, color_type, interlace_type;
854 png_byte **row_pointers = NULL;
855 FILE *fp = fopen(file_name, "rb");
858 cerr << file_name << " not found" << endl;
862 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
866 info_ptr = png_create_info_struct(png_ptr);
867 if (info_ptr == NULL)
870 if (setjmp(png_jmpbuf(png_ptr)))
873 png_init_io(png_ptr, fp);
874 png_read_png(png_ptr, info_ptr,
875 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
877 png_get_IHDR(png_ptr, info_ptr, &width, &height,
878 &bit_depth, &color_type, &interlace_type, NULL, NULL);
880 if (bit_depth != 8) // transform SHOULD handle this...
883 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
886 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
889 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
890 row_pointers = png_get_rows(png_ptr, info_ptr);
895 png_byte *dst = tex.data;
896 for (int i = height - 1; i >= 0; i--) {
897 png_byte *src = row_pointers[i];
898 for (unsigned j = 0; j < width; j++) {
910 png_byte *dst = tex.data;
911 int pitch = width * 4;
912 for (int i = height - 1; i >= 0; i--, dst += pitch)
913 memcpy(dst, row_pointers[i], pitch);
923 cerr << "There was a problem loading " << file_name << endl;
925 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
932 bool save_image(const char *file_name)
934 const char *ptr = strrchr((char *)file_name, '.');
936 if (strcasecmp(ptr + 1, "png") == 0)
937 return save_png(file_name);
940 STUBBED("Unsupported image type");
945 static bool save_png(const char *file_name)
948 png_structp png_ptr = NULL;
949 png_infop info_ptr = NULL;
952 fp = fopen(file_name, "wb");
956 png_bytep *row_pointers = new png_bytep[kContextHeight];
957 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
958 if ((!screenshot) || (!row_pointers))
962 glReadPixels(0, 0, kContextWidth, kContextHeight,
963 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
964 if (glGetError() != GL_NO_ERROR)
967 for (int i = 0; i < kContextHeight; i++)
968 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
970 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
974 info_ptr = png_create_info_struct(png_ptr);
975 if (info_ptr == NULL)
978 if (setjmp(png_jmpbuf(png_ptr)))
981 png_init_io(png_ptr, fp);
983 if (setjmp(png_jmpbuf(png_ptr)))
986 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
987 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
988 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
990 png_write_info(png_ptr, info_ptr);
992 if (setjmp(png_jmpbuf(png_ptr)))
995 png_write_image(png_ptr, row_pointers);
997 if (setjmp(png_jmpbuf(png_ptr)))
1000 png_write_end(png_ptr, NULL);
1004 png_destroy_write_struct(&png_ptr, &info_ptr);
1005 delete[] screenshot;
1006 delete[] row_pointers;
1010 unlink(ConvertFileName(file_name));