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 static int _argc = 0;
126 static char **_argv = NULL;
128 bool cmdline(const char *cmd)
130 for (int i = 1; i < _argc; i++) {
131 char *arg = _argv[i];
134 if (strcasecmp(arg, cmd) == 0)
141 //-----------------------------------------------------------------------------------------------------------------------
147 glClear( GL_COLOR_BUFFER_BIT );
151 glDisable( GL_ALPHA_TEST);
152 glDisable( GL_BLEND);
153 glDisable( GL_DEPTH_TEST);
155 glDisable( GL_LIGHTING);
156 glDisable( GL_LOGIC_OP);
157 glDisable( GL_TEXTURE_1D);
158 glDisable( GL_TEXTURE_2D);
159 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
160 glPixelTransferi( GL_RED_SCALE, 1);
161 glPixelTransferi( GL_RED_BIAS, 0);
162 glPixelTransferi( GL_GREEN_SCALE, 1);
163 glPixelTransferi( GL_GREEN_BIAS, 0);
164 glPixelTransferi( GL_BLUE_SCALE, 1);
165 glPixelTransferi( GL_BLUE_BIAS, 0);
166 glPixelTransferi( GL_ALPHA_SCALE, 1);
167 glPixelTransferi( GL_ALPHA_BIAS, 0);
169 // set initial rendering states
170 glShadeModel( GL_SMOOTH);
172 glDepthFunc( GL_LEQUAL);
173 glDepthMask( GL_TRUE);
174 glEnable( GL_DEPTH_TEST);
175 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
176 glCullFace( GL_FRONT);
177 glEnable( GL_CULL_FACE);
178 glEnable( GL_LIGHTING);
179 glEnable( GL_DITHER);
180 glEnable( GL_COLOR_MATERIAL);
181 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
182 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
183 glAlphaFunc( GL_GREATER, 0.5f);
185 if ( CanInitStereo(stereomode) ) {
186 InitStereo(stereomode);
188 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
189 stereomode = stereoNone;
193 void toggleFullscreen()
195 fullscreen = !fullscreen;
196 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
197 if (flags & SDL_WINDOW_FULLSCREEN) {
198 flags &= ~SDL_WINDOW_FULLSCREEN;
200 flags |= SDL_WINDOW_FULLSCREEN;
202 SDL_SetWindowFullscreen(sdlwindow, flags);
205 SDL_bool sdlEventProc(const SDL_Event &e)
211 case SDL_WINDOWEVENT:
212 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
217 case SDL_MOUSEMOTION:
218 deltah += e.motion.xrel;
219 deltav += e.motion.yrel;
223 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
224 (e.key.keysym.mod & KMOD_CTRL)) {
225 SDL_bool mode = SDL_TRUE;
226 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
227 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
228 SDL_SetWindowGrab(sdlwindow, mode);
229 SDL_SetRelativeMouseMode(mode);
230 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
240 // --------------------------------------------------------------------------
242 static Point gMidPoint;
255 if (!SDL_WasInit(SDL_INIT_VIDEO))
256 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
257 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
260 if (!LoadSettings()) {
261 fprintf(stderr, "Failed to load config, creating default\n");
264 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
268 if (SDL_GL_LoadLibrary(NULL) == -1) {
269 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
274 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
275 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
276 SDL_DisplayMode mode;
277 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
279 if ((mode.w < 640) || (mode.h < 480))
280 continue; // sane lower limit.
281 pair<int,int> resolution(mode.w, mode.h);
282 resolutions.insert(resolution);
286 if (resolutions.empty()) {
287 const std::string error = "No suitable video resolutions found.";
288 cerr << error << endl;
289 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
294 if (cmdline("showresolutions")) {
295 printf("Available resolutions:\n");
296 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
297 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
301 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
302 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
304 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
305 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
307 sdlflags |= SDL_WINDOW_FULLSCREEN;
309 if (!cmdline("nomousegrab"))
310 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
312 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
313 kContextWidth, kContextHeight, sdlflags);
316 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
317 fprintf(stderr, "forcing 640x480...\n");
319 kContextHeight = 480;
320 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
321 kContextWidth, kContextHeight, sdlflags);
323 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
324 fprintf(stderr, "forcing 640x480 windowed mode...\n");
325 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
326 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
327 kContextWidth, kContextHeight, sdlflags);
330 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
336 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
338 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
343 SDL_GL_MakeCurrent(sdlwindow, glctx);
345 if (!lookup_all_glsyms()) {
346 fprintf(stderr, "Missing required OpenGL functions.\n");
352 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
354 fprintf(stderr, "Failed to get a double-buffered context.\n");
359 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
360 SDL_GL_SetSwapInterval(1);
363 if (!cmdline("nomousegrab"))
364 SDL_SetRelativeMouseMode(SDL_TRUE);
368 GLint width = kContextWidth;
369 GLint height = kContextHeight;
370 gMidPoint.h = width / 2;
371 gMidPoint.v = height / 2;
373 screenheight = height;
376 newscreenwidth = screenwidth;
377 newscreenheight = screenheight;
379 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
380 pair<int,int> startresolution(width,height);
381 if (resolutions.find(startresolution) == resolutions.end()) {
382 resolutions.insert(startresolution);
391 static void DoMouse()
394 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
395 deltah *= usermousesensitivity;
396 deltav *= usermousesensitivity;
397 mousecoordh += deltah;
398 mousecoordv += deltav;
401 else if (mousecoordh >= kContextWidth)
402 mousecoordh = kContextWidth - 1;
405 else if (mousecoordv >= kContextHeight)
406 mousecoordv = kContextHeight - 1;
411 void DoFrameRate (int update)
413 static long frames = 0;
415 static AbsoluteTime time = {0, 0};
416 static AbsoluteTime frametime = {0, 0};
417 AbsoluteTime currTime = UpTime ();
418 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
420 if (0 > deltaTime) // if negative microseconds
421 deltaTime /= -1000000.0;
422 else // else milliseconds
425 multiplier = deltaTime;
426 if (multiplier < .001)
431 frametime = currTime; // reset for next time interval
433 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
435 if (0 > deltaTime) // if negative microseconds
436 deltaTime /= -1000000.0;
437 else // else milliseconds
440 if (0.001 <= deltaTime) { // has update interval passed
442 time = currTime; // reset for next time interval
451 static float sps = 200;
453 static float oldmult;
459 fps = 1 / multiplier;
461 count = multiplier * sps;
465 realmultiplier = multiplier;
466 multiplier *= gamespeed;
473 multiplier *= .00001;
474 if (slomo && !mainmenu)
475 multiplier *= slomospeed;
476 oldmult = multiplier;
477 multiplier /= (float)count;
483 for (int i = 0; i < count; i++) {
486 multiplier = oldmult;
489 /* - Debug code to test how many channels were active on average per frame
490 static long frames = 0;
492 static AbsoluteTime start = {0,0};
493 AbsoluteTime currTime = UpTime ();
494 static int num_channels = 0;
496 num_channels += OPENAL_GetChannelsPlaying();
497 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
499 if (0 > deltaTime) // if negative microseconds
500 deltaTime /= -1000000.0;
501 else // else milliseconds
509 float avg_channels = (float)num_channels / (float)frames;
511 ofstream opstream("log.txt",ios::app);
512 opstream << "Average frame count: ";
514 opstream << " frames - ";
515 opstream << avg_channels;
516 opstream << " per frame.\n";
523 if ( stereomode == stereoNone ) {
524 DrawGLScene(stereoCenter);
526 DrawGLScene(stereoLeft);
527 DrawGLScene(stereoRight);
531 // --------------------------------------------------------------------------
539 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
540 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
543 // cheat here...static destructors are calling glDeleteTexture() after
544 // the context is destroyed and libGL unloaded by SDL_Quit().
545 pglDeleteTextures = glDeleteTextures_doNothing;
546 #endif // __MINGW32__
550 // --------------------------------------------------------------------------
552 static bool IsFocused()
554 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
560 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
561 static char *findBinaryInPath(const char *bin, char *envr)
563 size_t alloc_size = 0;
570 ptr = strchr(start, ':'); /* find next $PATH separator. */
574 size = strlen(start) + strlen(bin) + 2;
575 if (size > alloc_size) {
576 char *x = (char *) realloc(exe, size);
587 /* build full binary path... */
589 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
593 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
594 strcpy(exe, start); /* i'm lazy. piss off. */
598 start = ptr + 1; /* start points to beginning of next element. */
599 } while (ptr != NULL);
604 return(NULL); /* doesn't exist in path. */
605 } /* findBinaryInPath */
608 char *calcBaseDir(const char *argv0)
610 /* If there isn't a path on argv0, then look through the $PATH for it. */
614 if (strchr(argv0, '/')) {
615 retval = strdup(argv0);
617 *((char *) strrchr(retval, '/')) = '\0';
621 envr = getenv("PATH");
627 retval = findBinaryInPath(argv0, envr);
632 static inline void chdirToAppPath(const char *argv0)
634 char *dir = calcBaseDir(argv0);
636 #if (defined(__APPLE__) && defined(__MACH__))
637 // Chop off /Contents/MacOS if it's at the end of the string, so we
638 // land in the base of the app bundle.
639 const size_t len = strlen(dir);
640 const char *bundledirs = "/Contents/MacOS";
641 const size_t bundledirslen = strlen(bundledirs);
642 if (len > bundledirslen) {
643 char *ptr = (dir + len) - bundledirslen;
644 if (strcasecmp(ptr, bundledirs) == 0)
655 int main(int argc, char **argv)
660 // !!! FIXME: we could use a Win32 API for this. --ryan.
662 chdirToAppPath(argv[0]);
674 bool gameDone = false;
675 bool gameFocused = true;
677 while (!gameDone && !tryquit) {
681 // check windows messages
688 while ( SDL_PollEvent( &e ) ) {
689 if (!sdlEventProc(e)) {
700 // allow game chance to pause
705 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
716 } catch (const std::exception& error) {
719 std::string e = "Caught exception: ";
724 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);