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/>.
23 #include "Audio/openal_wrapper.hpp"
24 #include "Graphic/gamegl.hpp"
25 #include "MacCompatibility.hpp"
26 #include "User/Settings.hpp"
41 #include "win-res/resource.hpp"
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 int difficulty;
60 extern SDL_Window *sdlwindow;
64 set<pair<int,int>> resolutions;
66 // statics/globals (internal only) ------------------------------------------
73 //-----------------------------------------------------------------------------------------------------------------------
79 glClear( GL_COLOR_BUFFER_BIT );
83 glDisable( GL_ALPHA_TEST);
85 glDisable( GL_DEPTH_TEST);
87 glDisable( GL_LIGHTING);
88 glDisable( GL_LOGIC_OP);
89 glDisable( GL_TEXTURE_1D);
90 glDisable( GL_TEXTURE_2D);
91 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
92 glPixelTransferi( GL_RED_SCALE, 1);
93 glPixelTransferi( GL_RED_BIAS, 0);
94 glPixelTransferi( GL_GREEN_SCALE, 1);
95 glPixelTransferi( GL_GREEN_BIAS, 0);
96 glPixelTransferi( GL_BLUE_SCALE, 1);
97 glPixelTransferi( GL_BLUE_BIAS, 0);
98 glPixelTransferi( GL_ALPHA_SCALE, 1);
99 glPixelTransferi( GL_ALPHA_BIAS, 0);
101 // set initial rendering states
102 glShadeModel( GL_SMOOTH);
104 glDepthFunc( GL_LEQUAL);
105 glDepthMask( GL_TRUE);
106 glEnable( GL_DEPTH_TEST);
107 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
108 glCullFace( GL_FRONT);
109 glEnable( GL_CULL_FACE);
110 glEnable( GL_LIGHTING);
111 glEnable( GL_DITHER);
112 glEnable( GL_COLOR_MATERIAL);
113 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
114 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
115 glAlphaFunc( GL_GREATER, 0.5f);
117 if ( CanInitStereo(stereomode) ) {
118 InitStereo(stereomode);
120 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
121 stereomode = stereoNone;
125 void toggleFullscreen()
127 fullscreen = !fullscreen;
128 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
129 if (flags & SDL_WINDOW_FULLSCREEN) {
130 flags &= ~SDL_WINDOW_FULLSCREEN;
132 flags |= SDL_WINDOW_FULLSCREEN;
134 SDL_SetWindowFullscreen(sdlwindow, flags);
137 SDL_bool sdlEventProc(const SDL_Event &e)
143 case SDL_WINDOWEVENT:
144 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
149 case SDL_MOUSEMOTION:
150 deltah += e.motion.xrel;
151 deltav += e.motion.yrel;
155 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
156 (e.key.keysym.mod & KMOD_CTRL)) {
157 SDL_bool mode = SDL_TRUE;
158 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
159 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
160 SDL_SetWindowGrab(sdlwindow, mode);
161 SDL_SetRelativeMouseMode(mode);
162 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
170 // --------------------------------------------------------------------------
172 static Point gMidPoint;
185 if (!SDL_WasInit(SDL_INIT_VIDEO))
186 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
187 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
190 if (!LoadSettings()) {
191 fprintf(stderr, "Failed to load config, creating default\n");
195 if (SDL_GL_LoadLibrary(NULL) == -1) {
196 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
201 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
202 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
203 SDL_DisplayMode mode;
204 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
206 if ((mode.w < 640) || (mode.h < 480))
207 continue; // sane lower limit.
208 pair<int,int> resolution(mode.w, mode.h);
209 resolutions.insert(resolution);
213 if (resolutions.empty()) {
214 const std::string error = "No suitable video resolutions found.";
215 cerr << error << endl;
216 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
221 if (commandLineOptions[SHOWRESOLUTIONS]) {
222 printf("Available resolutions:\n");
223 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
224 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
228 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
229 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
231 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
232 if (commandLineOptions[FULLSCREEN]) {
233 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
236 sdlflags |= SDL_WINDOW_FULLSCREEN;
238 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
239 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
242 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
243 kContextWidth, kContextHeight, sdlflags);
246 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
247 fprintf(stderr, "forcing 640x480...\n");
249 kContextHeight = 480;
250 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
251 kContextWidth, kContextHeight, sdlflags);
253 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
254 fprintf(stderr, "forcing 640x480 windowed mode...\n");
255 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
256 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
257 kContextWidth, kContextHeight, sdlflags);
260 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
266 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
268 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
273 SDL_GL_MakeCurrent(sdlwindow, glctx);
276 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
278 fprintf(stderr, "Failed to get a double-buffered context.\n");
283 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
284 SDL_GL_SetSwapInterval(1);
287 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
288 SDL_SetRelativeMouseMode(SDL_TRUE);
293 GLint width = kContextWidth;
294 GLint height = kContextHeight;
295 gMidPoint.h = width / 2;
296 gMidPoint.v = height / 2;
298 screenheight = height;
301 newscreenwidth = screenwidth;
302 newscreenheight = screenheight;
304 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
305 pair<int,int> startresolution(width,height);
306 if (resolutions.find(startresolution) == resolutions.end()) {
307 resolutions.insert(startresolution);
316 static void DoMouse()
319 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
320 deltah *= usermousesensitivity;
321 deltav *= usermousesensitivity;
322 mousecoordh += deltah;
323 mousecoordv += deltav;
326 else if (mousecoordh >= kContextWidth)
327 mousecoordh = kContextWidth - 1;
330 else if (mousecoordv >= kContextHeight)
331 mousecoordv = kContextHeight - 1;
336 void DoFrameRate (int update)
338 static long frames = 0;
340 static AbsoluteTime time = {0, 0};
341 static AbsoluteTime frametime = {0, 0};
342 AbsoluteTime currTime = UpTime ();
343 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
345 if (0 > deltaTime) // if negative microseconds
346 deltaTime /= -1000000.0;
347 else // else milliseconds
350 multiplier = deltaTime;
351 if (multiplier < .001)
356 frametime = currTime; // reset for next time interval
358 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
360 if (0 > deltaTime) // if negative microseconds
361 deltaTime /= -1000000.0;
362 else // else milliseconds
365 if (0.001 <= deltaTime) { // has update interval passed
367 time = currTime; // reset for next time interval
376 static float sps = 200;
378 static float oldmult;
384 fps = 1 / multiplier;
386 count = multiplier * sps;
390 realmultiplier = multiplier;
391 multiplier *= gamespeed;
398 multiplier *= .00001;
399 if (slomo && !mainmenu)
400 multiplier *= slomospeed;
401 oldmult = multiplier;
402 multiplier /= (float)count;
408 for (int i = 0; i < count; i++) {
411 multiplier = oldmult;
414 /* - Debug code to test how many channels were active on average per frame
415 static long frames = 0;
417 static AbsoluteTime start = {0,0};
418 AbsoluteTime currTime = UpTime ();
419 static int num_channels = 0;
421 num_channels += OPENAL_GetChannelsPlaying();
422 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
424 if (0 > deltaTime) // if negative microseconds
425 deltaTime /= -1000000.0;
426 else // else milliseconds
434 float avg_channels = (float)num_channels / (float)frames;
436 ofstream opstream("log.txt",ios::app);
437 opstream << "Average frame count: ";
439 opstream << " frames - ";
440 opstream << avg_channels;
441 opstream << " per frame.\n";
448 if ( stereomode == stereoNone ) {
449 DrawGLScene(stereoCenter);
451 DrawGLScene(stereoLeft);
452 DrawGLScene(stereoRight);
456 // --------------------------------------------------------------------------
463 delete[] commandLineOptionsBuffer;
468 // --------------------------------------------------------------------------
470 static bool IsFocused()
472 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
478 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
479 static char *findBinaryInPath(const char *bin, char *envr)
481 size_t alloc_size = 0;
488 ptr = strchr(start, ':'); /* find next $PATH separator. */
492 size = strlen(start) + strlen(bin) + 2;
493 if (size > alloc_size) {
494 char *x = (char *) realloc(exe, size);
505 /* build full binary path... */
507 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
511 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
512 strcpy(exe, start); /* i'm lazy. piss off. */
516 start = ptr + 1; /* start points to beginning of next element. */
517 } while (ptr != NULL);
522 return(NULL); /* doesn't exist in path. */
523 } /* findBinaryInPath */
526 char *calcBaseDir(const char *argv0)
528 /* If there isn't a path on argv0, then look through the $PATH for it. */
532 if (strchr(argv0, '/')) {
533 retval = strdup(argv0);
535 *((char *) strrchr(retval, '/')) = '\0';
539 envr = getenv("PATH");
545 retval = findBinaryInPath(argv0, envr);
550 static inline void chdirToAppPath(const char *argv0)
552 char *dir = calcBaseDir(argv0);
554 #if (defined(__APPLE__) && defined(__MACH__))
555 // Chop off /Contents/MacOS if it's at the end of the string, so we
556 // land in the base of the app bundle.
557 const size_t len = strlen(dir);
558 const char *bundledirs = "/Contents/MacOS";
559 const size_t bundledirslen = strlen(bundledirs);
560 if (len > bundledirslen) {
561 char *ptr = (dir + len) - bundledirslen;
562 if (strcasecmp(ptr, bundledirs) == 0)
572 const option::Descriptor usage[] =
574 {UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
576 {HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
577 {FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
578 {FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
579 {NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
580 {NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
581 {SOUND, OPENAL_OUTPUT_NOSOUND, "", "nosound", option::Arg::None, " --nosound Disable sound." },
582 {SOUND, OPENAL_OUTPUT_ALSA, "", "force-alsa", option::Arg::None, " --force-alsa Force use of ALSA back-end." },
583 {SOUND, OPENAL_OUTPUT_OSS, "", "force-oss", option::Arg::None, " --force-oss Force use of OSS back-end." },
584 {OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
585 {SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
586 {DEVTOOLS, 0, "d", "devtools", option::Arg::None, " -d, --devtools Enable dev tools: console, level editor and debug info." },
590 option::Option commandLineOptions[commandLineOptionsNumber];
591 option::Option* commandLineOptionsBuffer;
593 int main(int argc, char **argv)
595 argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
596 option::Stats stats(true, usage, argc, argv);
597 if (commandLineOptionsNumber != stats.options_max) {
598 std::cerr << "Found incorrect command line option number" << std::endl;
601 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
602 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
605 delete[] commandLineOptionsBuffer;
609 if (commandLineOptions[HELP]) {
610 option::printUsage(std::cout, usage);
611 delete[] commandLineOptionsBuffer;
615 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
616 std::cerr << "Unknown option: " << opt->name << "\n";
617 option::printUsage(std::cerr, usage);
618 delete[] commandLineOptionsBuffer;
622 // !!! FIXME: we could use a Win32 API for this. --ryan.
624 chdirToAppPath(argv[0]);
636 delete[] commandLineOptionsBuffer;
640 if (commandLineOptions[DEVTOOLS]) {
644 bool gameDone = false;
645 bool gameFocused = true;
647 while (!gameDone && !tryquit) {
651 // check windows messages
658 while ( SDL_PollEvent( &e ) ) {
659 if (!sdlEventProc(e)) {
670 // allow game chance to pause
675 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
687 } catch (const std::exception& error) {
690 std::string e = "Caught exception: ";
695 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);