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"
39 #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;
57 extern int difficulty;
59 extern SDL_Window* sdlwindow;
63 set<pair<int, int>> resolutions;
65 // statics/globals (internal only) ------------------------------------------
72 //-----------------------------------------------------------------------------------------------------------------------
78 glClear(GL_COLOR_BUFFER_BIT);
82 glDisable(GL_ALPHA_TEST);
84 glDisable(GL_DEPTH_TEST);
86 glDisable(GL_LIGHTING);
87 glDisable(GL_LOGIC_OP);
88 glDisable(GL_TEXTURE_1D);
89 glDisable(GL_TEXTURE_2D);
90 glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
91 glPixelTransferi(GL_RED_SCALE, 1);
92 glPixelTransferi(GL_RED_BIAS, 0);
93 glPixelTransferi(GL_GREEN_SCALE, 1);
94 glPixelTransferi(GL_GREEN_BIAS, 0);
95 glPixelTransferi(GL_BLUE_SCALE, 1);
96 glPixelTransferi(GL_BLUE_BIAS, 0);
97 glPixelTransferi(GL_ALPHA_SCALE, 1);
98 glPixelTransferi(GL_ALPHA_BIAS, 0);
100 // set initial rendering states
101 glShadeModel(GL_SMOOTH);
103 glDepthFunc(GL_LEQUAL);
104 glDepthMask(GL_TRUE);
105 glEnable(GL_DEPTH_TEST);
106 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
107 glCullFace(GL_FRONT);
108 glEnable(GL_CULL_FACE);
109 glEnable(GL_LIGHTING);
111 glEnable(GL_COLOR_MATERIAL);
112 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
113 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
114 glAlphaFunc(GL_GREATER, 0.5f);
116 if (CanInitStereo(stereomode)) {
117 InitStereo(stereomode);
119 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
120 stereomode = stereoNone;
124 void toggleFullscreen()
126 fullscreen = !fullscreen;
127 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
128 if (flags & SDL_WINDOW_FULLSCREEN) {
129 flags &= ~SDL_WINDOW_FULLSCREEN;
131 flags |= SDL_WINDOW_FULLSCREEN;
133 SDL_SetWindowFullscreen(sdlwindow, flags);
136 SDL_bool sdlEventProc(const SDL_Event& e)
142 case SDL_WINDOWEVENT:
143 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
148 case SDL_MOUSEMOTION:
149 deltah += e.motion.xrel;
150 deltav += e.motion.yrel;
154 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
155 (e.key.keysym.mod & KMOD_CTRL)) {
156 SDL_bool mode = SDL_TRUE;
157 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
158 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
159 SDL_SetWindowGrab(sdlwindow, mode);
160 SDL_SetRelativeMouseMode(mode);
161 } else if ((e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT)) {
169 // --------------------------------------------------------------------------
171 static Point gMidPoint;
184 if (!SDL_WasInit(SDL_INIT_VIDEO))
185 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
186 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
189 if (!LoadSettings()) {
190 fprintf(stderr, "Failed to load config, creating default\n");
194 if (SDL_GL_LoadLibrary(NULL) == -1) {
195 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
200 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
201 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
202 SDL_DisplayMode mode;
203 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
205 if ((mode.w < 640) || (mode.h < 480))
206 continue; // sane lower limit.
207 pair<int, int> resolution(mode.w, mode.h);
208 resolutions.insert(resolution);
212 if (resolutions.empty()) {
213 const std::string error = "No suitable video resolutions found.";
214 cerr << error << endl;
215 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
220 if (commandLineOptions[SHOWRESOLUTIONS]) {
221 printf("Available resolutions:\n");
222 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
223 printf(" %d x %d\n", (int)resolution->first, (int)resolution->second);
227 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
228 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
230 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
231 if (commandLineOptions[FULLSCREEN]) {
232 fullscreen = commandLineOptions[FULLSCREEN].last()->type();
235 sdlflags |= SDL_WINDOW_FULLSCREEN;
237 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
238 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
241 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
242 kContextWidth, kContextHeight, sdlflags);
245 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
246 fprintf(stderr, "forcing 640x480...\n");
248 kContextHeight = 480;
249 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
250 kContextWidth, kContextHeight, sdlflags);
252 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
253 fprintf(stderr, "forcing 640x480 windowed mode...\n");
254 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
255 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
256 kContextWidth, kContextHeight, sdlflags);
259 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
265 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
267 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
272 SDL_GL_MakeCurrent(sdlwindow, glctx);
275 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf)) {
276 fprintf(stderr, "Failed to get a double-buffered context.\n");
281 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
282 SDL_GL_SetSwapInterval(1);
285 if (!commandLineOptions[NOMOUSEGRAB].last()->type()) {
286 SDL_SetRelativeMouseMode(SDL_TRUE);
291 GLint width = kContextWidth;
292 GLint height = kContextHeight;
293 gMidPoint.h = width / 2;
294 gMidPoint.v = height / 2;
296 screenheight = height;
299 newscreenwidth = screenwidth;
300 newscreenheight = screenheight;
302 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
303 pair<int, int> startresolution(width, height);
304 if (resolutions.find(startresolution) == resolutions.end()) {
305 resolutions.insert(startresolution);
313 static void DoMouse()
316 if (mainmenu || ((abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000))) {
317 deltah *= usermousesensitivity;
318 deltav *= usermousesensitivity;
319 mousecoordh += deltah;
320 mousecoordv += deltav;
323 else if (mousecoordh >= kContextWidth)
324 mousecoordh = kContextWidth - 1;
327 else if (mousecoordv >= kContextHeight)
328 mousecoordv = kContextHeight - 1;
332 void DoFrameRate(int update)
334 static long frames = 0;
336 static AbsoluteTime time = { 0, 0 };
337 static AbsoluteTime frametime = { 0, 0 };
338 AbsoluteTime currTime = UpTime();
339 double deltaTime = (float)AbsoluteDeltaToDuration(currTime, frametime);
341 if (0 > deltaTime) // if negative microseconds
342 deltaTime /= -1000000.0;
343 else // else milliseconds
346 multiplier = deltaTime;
347 if (multiplier < .001)
352 frametime = currTime; // reset for next time interval
354 deltaTime = (float)AbsoluteDeltaToDuration(currTime, time);
356 if (0 > deltaTime) // if negative microseconds
357 deltaTime /= -1000000.0;
358 else // else milliseconds
361 if (0.001 <= deltaTime) { // has update interval passed
363 time = currTime; // reset for next time interval
371 static float sps = 200;
373 static float oldmult;
379 fps = 1 / multiplier;
381 count = multiplier * sps;
385 realmultiplier = multiplier;
386 multiplier *= gamespeed;
393 multiplier *= .00001;
394 if (slomo && !mainmenu)
395 multiplier *= slomospeed;
396 oldmult = multiplier;
397 multiplier /= (float)count;
403 for (int i = 0; i < count; i++) {
406 multiplier = oldmult;
409 /* - Debug code to test how many channels were active on average per frame
410 static long frames = 0;
412 static AbsoluteTime start = {0,0};
413 AbsoluteTime currTime = UpTime ();
414 static int num_channels = 0;
416 num_channels += OPENAL_GetChannelsPlaying();
417 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
419 if (0 > deltaTime) // if negative microseconds
420 deltaTime /= -1000000.0;
421 else // else milliseconds
429 float avg_channels = (float)num_channels / (float)frames;
431 ofstream opstream("log.txt",ios::app);
432 opstream << "Average frame count: ";
434 opstream << " frames - ";
435 opstream << avg_channels;
436 opstream << " per frame.\n";
443 if (stereomode == stereoNone) {
444 DrawGLScene(stereoCenter);
446 DrawGLScene(stereoLeft);
447 DrawGLScene(stereoRight);
451 // --------------------------------------------------------------------------
457 delete[] commandLineOptionsBuffer;
462 // --------------------------------------------------------------------------
464 static bool IsFocused()
466 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
470 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
471 static char* findBinaryInPath(const char* bin, char* envr)
473 size_t alloc_size = 0;
480 ptr = strchr(start, ':'); /* find next $PATH separator. */
484 size = strlen(start) + strlen(bin) + 2;
485 if (size > alloc_size) {
486 char* x = (char*)realloc(exe, size);
497 /* build full binary path... */
499 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
503 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
504 strcpy(exe, start); /* i'm lazy. piss off. */
508 start = ptr + 1; /* start points to beginning of next element. */
509 } while (ptr != NULL);
514 return (NULL); /* doesn't exist in path. */
515 } /* findBinaryInPath */
517 char* calcBaseDir(const char* argv0)
519 /* If there isn't a path on argv0, then look through the $PATH for it. */
523 if (strchr(argv0, '/')) {
524 retval = strdup(argv0);
526 *((char*)strrchr(retval, '/')) = '\0';
530 envr = getenv("PATH");
536 retval = findBinaryInPath(argv0, envr);
541 static inline void chdirToAppPath(const char* argv0)
543 char* dir = calcBaseDir(argv0);
545 #if (defined(__APPLE__) && defined(__MACH__))
546 // Chop off /Contents/MacOS if it's at the end of the string, so we
547 // land in the base of the app bundle.
548 const size_t len = strlen(dir);
549 const char* bundledirs = "/Contents/MacOS";
550 const size_t bundledirslen = strlen(bundledirs);
551 if (len > bundledirslen) {
552 char* ptr = (dir + len) - bundledirslen;
553 if (strcasecmp(ptr, bundledirs) == 0)
563 const option::Descriptor usage[] =
565 { UNKNOWN, 0, "", "", option::Arg::None, "USAGE: lugaru [options]\n\n"
567 { HELP, 0, "h", "help", option::Arg::None, " -h, --help Print usage and exit." },
568 { FULLSCREEN, 1, "f", "fullscreen", option::Arg::None, " -f, --fullscreen Start the game in fullscreen mode." },
569 { FULLSCREEN, 0, "w", "windowed", option::Arg::None, " -w, --windowed Start the game in windowed mode (default)." },
570 { NOMOUSEGRAB, 1, "", "nomousegrab", option::Arg::None, " --nomousegrab Disable mousegrab." },
571 { NOMOUSEGRAB, 0, "", "mousegrab", option::Arg::None, " --mousegrab Enable mousegrab (default)." },
572 { SOUND, 1, "", "nosound", option::Arg::None, " --nosound Disable sound." },
573 { OPENALINFO, 0, "", "openal-info", option::Arg::None, " --openal-info Print info about OpenAL at launch." },
574 { SHOWRESOLUTIONS, 0, "", "showresolutions", option::Arg::None, " --showresolutions List the resolutions found by SDL at launch." },
575 { DEVTOOLS, 0, "d", "devtools", option::Arg::None, " -d, --devtools Enable dev tools: console, level editor and debug info." },
579 option::Option commandLineOptions[commandLineOptionsNumber];
580 option::Option* commandLineOptionsBuffer;
582 int main(int argc, char** argv)
585 argv += (argc > 0); // skip program name argv[0] if present
586 option::Stats stats(true, usage, argc, argv);
587 if (commandLineOptionsNumber != stats.options_max) {
588 std::cerr << "Found incorrect command line option number" << std::endl;
591 commandLineOptionsBuffer = new option::Option[stats.buffer_max];
592 option::Parser parse(true, usage, argc, argv, commandLineOptions, commandLineOptionsBuffer);
595 delete[] commandLineOptionsBuffer;
599 if (commandLineOptions[HELP]) {
600 option::printUsage(std::cout, usage);
601 delete[] commandLineOptionsBuffer;
605 if (option::Option* opt = commandLineOptions[UNKNOWN]) {
606 std::cerr << "Unknown option: " << opt->name << "\n";
607 option::printUsage(std::cerr, usage);
608 delete[] commandLineOptionsBuffer;
612 // !!! FIXME: we could use a Win32 API for this. --ryan.
614 chdirToAppPath(argv[0]);
626 delete[] commandLineOptionsBuffer;
630 if (commandLineOptions[DEVTOOLS]) {
634 bool gameDone = false;
635 bool gameFocused = true;
637 while (!gameDone && !tryquit) {
641 // check windows messages
648 while (SDL_PollEvent(&e)) {
649 if (!sdlEventProc(e)) {
660 // allow game chance to pause
665 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
677 } catch (const std::exception& error) {
680 std::string e = "Caught exception: ";
685 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception catched", error.what(), NULL);