2 Copyright (C) 2003, 2010 - Wolfire Games
3 Copyright (C) 2010-2016 - Lugaru contributors (see AUTHORS file)
5 This file is part of Lugaru.
7 Lugaru is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 Lugaru is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
29 #include "MacCompatibility.h"
36 #include "openal_wrapper.h"
41 #include "win-res/resource.h"
44 extern float multiplier;
46 extern float realmultiplier;
48 extern bool cellophane;
49 extern float texdetail;
52 extern bool stillloading;
55 extern float slomospeed;
56 extern float slomofreq;
57 extern bool visibleloading;
59 extern SDL_Window *sdlwindow;
63 set<pair<int,int>> resolutions;
65 // statics/globals (internal only) ------------------------------------------
69 #pragma warning(disable: 4273)
72 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
73 #define GL_FUNC(ret,fn,params,call,rt) \
75 static ret (GLAPIENTRY *p##fn) params = NULL; \
76 ret GLAPIENTRY fn params { rt p##fn call; } \
86 static bool lookup_glsym(const char *funcname, void **func)
88 *func = SDL_GL_GetProcAddress(funcname);
90 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
96 static bool lookup_all_glsyms(void)
99 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
100 #define GL_FUNC(ret,fn,params,call,rt) \
101 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
104 #endif // __MINGW32__
108 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
109 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
113 #endif // __MINGW32__
118 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
125 //-----------------------------------------------------------------------------------------------------------------------
131 glClear( GL_COLOR_BUFFER_BIT );
135 glDisable( GL_ALPHA_TEST);
136 glDisable( GL_BLEND);
137 glDisable( GL_DEPTH_TEST);
139 glDisable( GL_LIGHTING);
140 glDisable( GL_LOGIC_OP);
141 glDisable( GL_TEXTURE_1D);
142 glDisable( GL_TEXTURE_2D);
143 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
144 glPixelTransferi( GL_RED_SCALE, 1);
145 glPixelTransferi( GL_RED_BIAS, 0);
146 glPixelTransferi( GL_GREEN_SCALE, 1);
147 glPixelTransferi( GL_GREEN_BIAS, 0);
148 glPixelTransferi( GL_BLUE_SCALE, 1);
149 glPixelTransferi( GL_BLUE_BIAS, 0);
150 glPixelTransferi( GL_ALPHA_SCALE, 1);
151 glPixelTransferi( GL_ALPHA_BIAS, 0);
153 // set initial rendering states
154 glShadeModel( GL_SMOOTH);
156 glDepthFunc( GL_LEQUAL);
157 glDepthMask( GL_TRUE);
158 glEnable( GL_DEPTH_TEST);
159 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
160 glCullFace( GL_FRONT);
161 glEnable( GL_CULL_FACE);
162 glEnable( GL_LIGHTING);
163 glEnable( GL_DITHER);
164 glEnable( GL_COLOR_MATERIAL);
165 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
166 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
167 glAlphaFunc( GL_GREATER, 0.5f);
169 if ( CanInitStereo(stereomode) ) {
170 InitStereo(stereomode);
172 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
173 stereomode = stereoNone;
177 void toggleFullscreen()
179 fullscreen = !fullscreen;
180 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
181 if (flags & SDL_WINDOW_FULLSCREEN) {
182 flags &= ~SDL_WINDOW_FULLSCREEN;
184 flags |= SDL_WINDOW_FULLSCREEN;
186 SDL_SetWindowFullscreen(sdlwindow, flags);
189 SDL_bool sdlEventProc(const SDL_Event &e)
195 case SDL_WINDOWEVENT:
196 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
201 case SDL_MOUSEMOTION:
202 deltah += e.motion.xrel;
203 deltav += e.motion.yrel;
207 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
208 (e.key.keysym.mod & KMOD_CTRL)) {
209 SDL_bool mode = SDL_TRUE;
210 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
211 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
212 SDL_SetWindowGrab(sdlwindow, mode);
213 SDL_SetRelativeMouseMode(mode);
214 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
222 // --------------------------------------------------------------------------
224 static Point gMidPoint;
237 if (!SDL_WasInit(SDL_INIT_VIDEO))
238 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
239 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
242 if (!LoadSettings()) {
243 fprintf(stderr, "Failed to load config, creating default\n");
246 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
250 if (SDL_GL_LoadLibrary(NULL) == -1) {
251 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
256 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
257 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
258 SDL_DisplayMode mode;
259 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
261 if ((mode.w < 640) || (mode.h < 480))
262 continue; // sane lower limit.
263 pair<int,int> resolution(mode.w, mode.h);
264 resolutions.insert(resolution);
268 if (resolutions.empty()) {
269 const std::string error = "No suitable video resolutions found.";
270 cerr << error << endl;
271 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
276 if (commandLineOptions[SHOWRESOLUTIONS]) {
277 printf("Available resolutions:\n");
278 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
279 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
283 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
284 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
286 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
287 if (commandLineOptions[FULLSCREEN]) {
288 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
291 sdlflags |= SDL_WINDOW_FULLSCREEN;
293 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
294 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
297 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
298 kContextWidth, kContextHeight, sdlflags);
301 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
302 fprintf(stderr, "forcing 640x480...\n");
304 kContextHeight = 480;
305 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
306 kContextWidth, kContextHeight, sdlflags);
308 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
309 fprintf(stderr, "forcing 640x480 windowed mode...\n");
310 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
311 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
312 kContextWidth, kContextHeight, sdlflags);
315 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
321 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
323 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
328 SDL_GL_MakeCurrent(sdlwindow, glctx);
330 if (!lookup_all_glsyms()) {
331 fprintf(stderr, "Missing required OpenGL functions.\n");
337 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
339 fprintf(stderr, "Failed to get a double-buffered context.\n");
344 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
345 SDL_GL_SetSwapInterval(1);
348 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
349 SDL_SetRelativeMouseMode(SDL_TRUE);
354 GLint width = kContextWidth;
355 GLint height = kContextHeight;
356 gMidPoint.h = width / 2;
357 gMidPoint.v = height / 2;
359 screenheight = height;
362 newscreenwidth = screenwidth;
363 newscreenheight = screenheight;
365 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
366 pair<int,int> startresolution(width,height);
367 if (resolutions.find(startresolution) == resolutions.end()) {
368 resolutions.insert(startresolution);
377 static void DoMouse()
380 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
381 deltah *= usermousesensitivity;
382 deltav *= usermousesensitivity;
383 mousecoordh += deltah;
384 mousecoordv += deltav;
387 else if (mousecoordh >= kContextWidth)
388 mousecoordh = kContextWidth - 1;
391 else if (mousecoordv >= kContextHeight)
392 mousecoordv = kContextHeight - 1;
397 void DoFrameRate (int update)
399 static long frames = 0;
401 static AbsoluteTime time = {0, 0};
402 static AbsoluteTime frametime = {0, 0};
403 AbsoluteTime currTime = UpTime ();
404 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
406 if (0 > deltaTime) // if negative microseconds
407 deltaTime /= -1000000.0;
408 else // else milliseconds
411 multiplier = deltaTime;
412 if (multiplier < .001)
417 frametime = currTime; // reset for next time interval
419 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
421 if (0 > deltaTime) // if negative microseconds
422 deltaTime /= -1000000.0;
423 else // else milliseconds
426 if (0.001 <= deltaTime) { // has update interval passed
428 time = currTime; // reset for next time interval
437 static float sps = 200;
439 static float oldmult;
445 fps = 1 / multiplier;
447 count = multiplier * sps;
451 realmultiplier = multiplier;
452 multiplier *= gamespeed;
459 multiplier *= .00001;
460 if (slomo && !mainmenu)
461 multiplier *= slomospeed;
462 oldmult = multiplier;
463 multiplier /= (float)count;
469 for (int i = 0; i < count; i++) {
472 multiplier = oldmult;
475 /* - Debug code to test how many channels were active on average per frame
476 static long frames = 0;
478 static AbsoluteTime start = {0,0};
479 AbsoluteTime currTime = UpTime ();
480 static int num_channels = 0;
482 num_channels += OPENAL_GetChannelsPlaying();
483 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
485 if (0 > deltaTime) // if negative microseconds
486 deltaTime /= -1000000.0;
487 else // else milliseconds
495 float avg_channels = (float)num_channels / (float)frames;
497 ofstream opstream("log.txt",ios::app);
498 opstream << "Average frame count: ";
500 opstream << " frames - ";
501 opstream << avg_channels;
502 opstream << " per frame.\n";
509 if ( stereomode == stereoNone ) {
510 DrawGLScene(stereoCenter);
512 DrawGLScene(stereoLeft);
513 DrawGLScene(stereoRight);
517 // --------------------------------------------------------------------------
525 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
526 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
529 // cheat here...static destructors are calling glDeleteTexture() after
530 // the context is destroyed and libGL unloaded by SDL_Quit().
531 pglDeleteTextures = glDeleteTextures_doNothing;
532 #endif // __MINGW32__
536 // --------------------------------------------------------------------------
538 static bool IsFocused()
540 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
546 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
547 static char *findBinaryInPath(const char *bin, char *envr)
549 size_t alloc_size = 0;
556 ptr = strchr(start, ':'); /* find next $PATH separator. */
560 size = strlen(start) + strlen(bin) + 2;
561 if (size > alloc_size) {
562 char *x = (char *) realloc(exe, size);
573 /* build full binary path... */
575 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
579 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
580 strcpy(exe, start); /* i'm lazy. piss off. */
584 start = ptr + 1; /* start points to beginning of next element. */
585 } while (ptr != NULL);
590 return(NULL); /* doesn't exist in path. */
591 } /* findBinaryInPath */
594 char *calcBaseDir(const char *argv0)
596 /* If there isn't a path on argv0, then look through the $PATH for it. */
600 if (strchr(argv0, '/')) {
601 retval = strdup(argv0);
603 *((char *) strrchr(retval, '/')) = '\0';
607 envr = getenv("PATH");
613 retval = findBinaryInPath(argv0, envr);
618 static inline void chdirToAppPath(const char *argv0)
620 char *dir = calcBaseDir(argv0);
622 #if (defined(__APPLE__) && defined(__MACH__))
623 // Chop off /Contents/MacOS if it's at the end of the string, so we
624 // land in the base of the app bundle.
625 const size_t len = strlen(dir);
626 const char *bundledirs = "/Contents/MacOS";
627 const size_t bundledirslen = strlen(bundledirs);
628 if (len > bundledirslen) {
629 char *ptr = (dir + len) - bundledirslen;
630 if (strcasecmp(ptr, bundledirs) == 0)
640 const option::Descriptor usage[] =
642 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
644 {HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
645 {FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
646 {FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
647 {NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
648 {NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
649 {SOUND, OPENAL_OUTPUT_NOSOUND, "", "nosound", option::Arg::None, " --nosound Disable sound." },
650 {SOUND, OPENAL_OUTPUT_ALSA, "", "force-alsa", option::Arg::None, " --force-alsa Force use of ALSA back-end." },
651 {SOUND, OPENAL_OUTPUT_OSS, "", "force-oss", option::Arg::None, " --force-oss Force use of OSS back-end." },
652 {OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
653 {SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
657 option::Option commandLineOptions[commandLineOptionsNumber];
659 int main(int argc, char **argv)
661 argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
662 option::Stats stats(true, usage, argc, argv);
663 if (commandLineOptionsNumber != stats.options_max) {
664 std::cerr << "Found incorrect command line option number" << std::endl;
667 option::Option buffer[stats.buffer_max];
668 option::Parser parse(true, usage, argc, argv, commandLineOptions, buffer);
674 if (commandLineOptions[HELP]) {
675 option::printUsage(std::cout, usage);
679 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
680 std::cerr << "Unknown option: " << opt->name << "\n";
681 option::printUsage(std::cerr, usage);
685 // !!! FIXME: we could use a Win32 API for this. --ryan.
687 chdirToAppPath(argv[0]);
699 bool gameDone = false;
700 bool gameFocused = true;
702 while (!gameDone && !tryquit) {
706 // check windows messages
713 while ( SDL_PollEvent( &e ) ) {
714 if (!sdlEventProc(e)) {
725 // allow game chance to pause
730 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
741 } catch (const std::exception& error) {
744 std::string e = "Caught exception: ";
749 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);