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;
45 extern float realmultiplier;
47 extern bool cellophane;
48 extern float texdetail;
51 extern bool stillloading;
54 extern float slomospeed;
55 extern float slomofreq;
56 extern bool visibleloading;
58 extern SDL_Window *sdlwindow;
62 set<pair<int,int>> resolutions;
64 // statics/globals (internal only) ------------------------------------------
68 #pragma warning(disable: 4273)
71 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
72 #define GL_FUNC(ret,fn,params,call,rt) \
74 static ret (GLAPIENTRY *p##fn) params = NULL; \
75 ret GLAPIENTRY fn params { rt p##fn call; } \
85 static bool lookup_glsym(const char *funcname, void **func)
87 *func = SDL_GL_GetProcAddress(funcname);
89 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
95 static bool lookup_all_glsyms(void)
98 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
99 #define GL_FUNC(ret,fn,params,call,rt) \
100 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
103 #endif // __MINGW32__
107 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
108 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
112 #endif // __MINGW32__
117 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
124 //-----------------------------------------------------------------------------------------------------------------------
130 glClear( GL_COLOR_BUFFER_BIT );
134 glDisable( GL_ALPHA_TEST);
135 glDisable( GL_BLEND);
136 glDisable( GL_DEPTH_TEST);
138 glDisable( GL_LIGHTING);
139 glDisable( GL_LOGIC_OP);
140 glDisable( GL_TEXTURE_1D);
141 glDisable( GL_TEXTURE_2D);
142 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
143 glPixelTransferi( GL_RED_SCALE, 1);
144 glPixelTransferi( GL_RED_BIAS, 0);
145 glPixelTransferi( GL_GREEN_SCALE, 1);
146 glPixelTransferi( GL_GREEN_BIAS, 0);
147 glPixelTransferi( GL_BLUE_SCALE, 1);
148 glPixelTransferi( GL_BLUE_BIAS, 0);
149 glPixelTransferi( GL_ALPHA_SCALE, 1);
150 glPixelTransferi( GL_ALPHA_BIAS, 0);
152 // set initial rendering states
153 glShadeModel( GL_SMOOTH);
155 glDepthFunc( GL_LEQUAL);
156 glDepthMask( GL_TRUE);
157 glEnable( GL_DEPTH_TEST);
158 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
159 glCullFace( GL_FRONT);
160 glEnable( GL_CULL_FACE);
161 glEnable( GL_LIGHTING);
162 glEnable( GL_DITHER);
163 glEnable( GL_COLOR_MATERIAL);
164 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
165 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
166 glAlphaFunc( GL_GREATER, 0.5f);
168 if ( CanInitStereo(stereomode) ) {
169 InitStereo(stereomode);
171 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
172 stereomode = stereoNone;
176 void toggleFullscreen()
178 fullscreen = !fullscreen;
179 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
180 if (flags & SDL_WINDOW_FULLSCREEN) {
181 flags &= ~SDL_WINDOW_FULLSCREEN;
183 flags |= SDL_WINDOW_FULLSCREEN;
185 SDL_SetWindowFullscreen(sdlwindow, flags);
188 SDL_bool sdlEventProc(const SDL_Event &e)
194 case SDL_WINDOWEVENT:
195 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
200 case SDL_MOUSEMOTION:
201 deltah += e.motion.xrel;
202 deltav += e.motion.yrel;
206 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
207 (e.key.keysym.mod & KMOD_CTRL)) {
208 SDL_bool mode = SDL_TRUE;
209 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
210 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
211 SDL_SetWindowGrab(sdlwindow, mode);
212 SDL_SetRelativeMouseMode(mode);
213 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
221 // --------------------------------------------------------------------------
223 static Point gMidPoint;
236 if (!SDL_WasInit(SDL_INIT_VIDEO))
237 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
238 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
241 if (!LoadSettings()) {
242 fprintf(stderr, "Failed to load config, creating default\n");
246 if (SDL_GL_LoadLibrary(NULL) == -1) {
247 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
252 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
253 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
254 SDL_DisplayMode mode;
255 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
257 if ((mode.w < 640) || (mode.h < 480))
258 continue; // sane lower limit.
259 pair<int,int> resolution(mode.w, mode.h);
260 resolutions.insert(resolution);
264 if (resolutions.empty()) {
265 const std::string error = "No suitable video resolutions found.";
266 cerr << error << endl;
267 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
272 if (commandLineOptions[SHOWRESOLUTIONS]) {
273 printf("Available resolutions:\n");
274 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
275 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
279 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
280 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
282 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
283 if (commandLineOptions[FULLSCREEN]) {
284 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
287 sdlflags |= SDL_WINDOW_FULLSCREEN;
289 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
290 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
293 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
294 kContextWidth, kContextHeight, sdlflags);
297 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
298 fprintf(stderr, "forcing 640x480...\n");
300 kContextHeight = 480;
301 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
302 kContextWidth, kContextHeight, sdlflags);
304 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
305 fprintf(stderr, "forcing 640x480 windowed mode...\n");
306 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
307 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
308 kContextWidth, kContextHeight, sdlflags);
311 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
317 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
319 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
324 SDL_GL_MakeCurrent(sdlwindow, glctx);
326 if (!lookup_all_glsyms()) {
327 fprintf(stderr, "Missing required OpenGL functions.\n");
333 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
335 fprintf(stderr, "Failed to get a double-buffered context.\n");
340 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
341 SDL_GL_SetSwapInterval(1);
344 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
345 SDL_SetRelativeMouseMode(SDL_TRUE);
350 GLint width = kContextWidth;
351 GLint height = kContextHeight;
352 gMidPoint.h = width / 2;
353 gMidPoint.v = height / 2;
355 screenheight = height;
358 newscreenwidth = screenwidth;
359 newscreenheight = screenheight;
361 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
362 pair<int,int> startresolution(width,height);
363 if (resolutions.find(startresolution) == resolutions.end()) {
364 resolutions.insert(startresolution);
373 static void DoMouse()
376 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
377 deltah *= usermousesensitivity;
378 deltav *= usermousesensitivity;
379 mousecoordh += deltah;
380 mousecoordv += deltav;
383 else if (mousecoordh >= kContextWidth)
384 mousecoordh = kContextWidth - 1;
387 else if (mousecoordv >= kContextHeight)
388 mousecoordv = kContextHeight - 1;
393 void DoFrameRate (int update)
395 static long frames = 0;
397 static AbsoluteTime time = {0, 0};
398 static AbsoluteTime frametime = {0, 0};
399 AbsoluteTime currTime = UpTime ();
400 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
402 if (0 > deltaTime) // if negative microseconds
403 deltaTime /= -1000000.0;
404 else // else milliseconds
407 multiplier = deltaTime;
408 if (multiplier < .001)
413 frametime = currTime; // reset for next time interval
415 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
417 if (0 > deltaTime) // if negative microseconds
418 deltaTime /= -1000000.0;
419 else // else milliseconds
422 if (0.001 <= deltaTime) { // has update interval passed
424 time = currTime; // reset for next time interval
433 static float sps = 200;
435 static float oldmult;
441 fps = 1 / multiplier;
443 count = multiplier * sps;
447 realmultiplier = multiplier;
448 multiplier *= gamespeed;
455 multiplier *= .00001;
456 if (slomo && !mainmenu)
457 multiplier *= slomospeed;
458 oldmult = multiplier;
459 multiplier /= (float)count;
465 for (int i = 0; i < count; i++) {
468 multiplier = oldmult;
471 /* - Debug code to test how many channels were active on average per frame
472 static long frames = 0;
474 static AbsoluteTime start = {0,0};
475 AbsoluteTime currTime = UpTime ();
476 static int num_channels = 0;
478 num_channels += OPENAL_GetChannelsPlaying();
479 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
481 if (0 > deltaTime) // if negative microseconds
482 deltaTime /= -1000000.0;
483 else // else milliseconds
491 float avg_channels = (float)num_channels / (float)frames;
493 ofstream opstream("log.txt",ios::app);
494 opstream << "Average frame count: ";
496 opstream << " frames - ";
497 opstream << avg_channels;
498 opstream << " per frame.\n";
505 if ( stereomode == stereoNone ) {
506 DrawGLScene(stereoCenter);
508 DrawGLScene(stereoLeft);
509 DrawGLScene(stereoRight);
513 // --------------------------------------------------------------------------
521 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
522 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
525 // cheat here...static destructors are calling glDeleteTexture() after
526 // the context is destroyed and libGL unloaded by SDL_Quit().
527 pglDeleteTextures = glDeleteTextures_doNothing;
528 #endif // __MINGW32__
532 // --------------------------------------------------------------------------
534 static bool IsFocused()
536 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
542 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
543 static char *findBinaryInPath(const char *bin, char *envr)
545 size_t alloc_size = 0;
552 ptr = strchr(start, ':'); /* find next $PATH separator. */
556 size = strlen(start) + strlen(bin) + 2;
557 if (size > alloc_size) {
558 char *x = (char *) realloc(exe, size);
569 /* build full binary path... */
571 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
575 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
576 strcpy(exe, start); /* i'm lazy. piss off. */
580 start = ptr + 1; /* start points to beginning of next element. */
581 } while (ptr != NULL);
586 return(NULL); /* doesn't exist in path. */
587 } /* findBinaryInPath */
590 char *calcBaseDir(const char *argv0)
592 /* If there isn't a path on argv0, then look through the $PATH for it. */
596 if (strchr(argv0, '/')) {
597 retval = strdup(argv0);
599 *((char *) strrchr(retval, '/')) = '\0';
603 envr = getenv("PATH");
609 retval = findBinaryInPath(argv0, envr);
614 static inline void chdirToAppPath(const char *argv0)
616 char *dir = calcBaseDir(argv0);
618 #if (defined(__APPLE__) && defined(__MACH__))
619 // Chop off /Contents/MacOS if it's at the end of the string, so we
620 // land in the base of the app bundle.
621 const size_t len = strlen(dir);
622 const char *bundledirs = "/Contents/MacOS";
623 const size_t bundledirslen = strlen(bundledirs);
624 if (len > bundledirslen) {
625 char *ptr = (dir + len) - bundledirslen;
626 if (strcasecmp(ptr, bundledirs) == 0)
636 const option::Descriptor usage[] =
638 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
640 {HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
641 {FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
642 {FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
643 {NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
644 {NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
645 {SOUND, OPENAL_OUTPUT_NOSOUND, "", "nosound", option::Arg::None, " --nosound Disable sound." },
646 {SOUND, OPENAL_OUTPUT_ALSA, "", "force-alsa", option::Arg::None, " --force-alsa Force use of ALSA back-end." },
647 {SOUND, OPENAL_OUTPUT_OSS, "", "force-oss", option::Arg::None, " --force-oss Force use of OSS back-end." },
648 {OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
649 {SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
653 option::Option commandLineOptions[commandLineOptionsNumber];
655 int main(int argc, char **argv)
657 argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
658 option::Stats stats(true, usage, argc, argv);
659 if (commandLineOptionsNumber != stats.options_max) {
660 std::cerr << "Found incorrect command line option number" << std::endl;
663 option::Option buffer[stats.buffer_max];
664 option::Parser parse(true, usage, argc, argv, commandLineOptions, buffer);
670 if (commandLineOptions[HELP]) {
671 option::printUsage(std::cout, usage);
675 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
676 std::cerr << "Unknown option: " << opt->name << "\n";
677 option::printUsage(std::cerr, usage);
681 // !!! FIXME: we could use a Win32 API for this. --ryan.
683 chdirToAppPath(argv[0]);
695 bool gameDone = false;
696 bool gameFocused = true;
698 while (!gameDone && !tryquit) {
702 // check windows messages
709 while ( SDL_PollEvent( &e ) ) {
710 if (!sdlEventProc(e)) {
721 // allow game chance to pause
726 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
737 } catch (const std::exception& error) {
740 std::string e = "Caught exception: ";
745 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);