2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
6 Lugaru is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 Lugaru is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
28 #include "MacCompatibility.h"
35 #include "openal_wrapper.h"
40 #include "win-res/resource.h"
43 extern float multiplier;
45 extern float realmultiplier;
47 extern bool cellophane;
48 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 static 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;
256 if (!SDL_WasInit(SDL_INIT_VIDEO))
257 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
258 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
261 if (!LoadSettings()) {
262 fprintf(stderr, "Failed to load config, creating default\n");
265 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
269 if (SDL_GL_LoadLibrary(NULL) == -1) {
270 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
275 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
276 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
277 SDL_DisplayMode mode;
278 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
280 if ((mode.w < 640) || (mode.h < 480))
281 continue; // sane lower limit.
282 pair<int,int> resolution(mode.w, mode.h);
283 resolutions.insert(resolution);
287 if (resolutions.empty()) {
288 const std::string error = "No suitable video resolutions found.";
289 cerr << error << endl;
290 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
295 if (cmdline("showresolutions")) {
296 printf("Available resolutions:\n");
297 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
298 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
302 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
303 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
305 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
306 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
308 sdlflags |= SDL_WINDOW_FULLSCREEN;
310 if (!cmdline("nomousegrab"))
311 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
313 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
314 kContextWidth, kContextHeight, sdlflags);
317 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
318 fprintf(stderr, "forcing 640x480...\n");
320 kContextHeight = 480;
321 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
322 kContextWidth, kContextHeight, sdlflags);
324 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
325 fprintf(stderr, "forcing 640x480 windowed mode...\n");
326 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
327 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
328 kContextWidth, kContextHeight, sdlflags);
331 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
337 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
339 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
344 SDL_GL_MakeCurrent(sdlwindow, glctx);
346 if (!lookup_all_glsyms()) {
347 fprintf(stderr, "Missing required OpenGL functions.\n");
353 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
355 fprintf(stderr, "Failed to get a double-buffered context.\n");
360 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
361 SDL_GL_SetSwapInterval(1);
364 if (!cmdline("nomousegrab"))
365 SDL_SetRelativeMouseMode(SDL_TRUE);
369 GLint width = kContextWidth;
370 GLint height = kContextHeight;
371 gMidPoint.h = width / 2;
372 gMidPoint.v = height / 2;
374 screenheight = height;
377 newscreenwidth = screenwidth;
378 newscreenheight = screenheight;
380 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
381 pair<int,int> startresolution(width,height);
382 if (resolutions.find(startresolution) == resolutions.end()) {
383 resolutions.insert(startresolution);
392 static void DoMouse()
395 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
396 deltah *= usermousesensitivity;
397 deltav *= usermousesensitivity;
398 mousecoordh += deltah;
399 mousecoordv += deltav;
402 else if (mousecoordh >= kContextWidth)
403 mousecoordh = kContextWidth - 1;
406 else if (mousecoordv >= kContextHeight)
407 mousecoordv = kContextHeight - 1;
412 void DoFrameRate (int update)
414 static long frames = 0;
416 static AbsoluteTime time = {0, 0};
417 static AbsoluteTime frametime = {0, 0};
418 AbsoluteTime currTime = UpTime ();
419 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
421 if (0 > deltaTime) // if negative microseconds
422 deltaTime /= -1000000.0;
423 else // else milliseconds
426 multiplier = deltaTime;
427 if (multiplier < .001)
432 frametime = currTime; // reset for next time interval
434 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
436 if (0 > deltaTime) // if negative microseconds
437 deltaTime /= -1000000.0;
438 else // else milliseconds
441 if (0.001 <= deltaTime) { // has update interval passed
443 time = currTime; // reset for next time interval
452 static float sps = 200;
454 static float oldmult;
460 fps = 1 / multiplier;
462 count = multiplier * sps;
466 realmultiplier = multiplier;
467 multiplier *= gamespeed;
474 multiplier *= .00001;
475 if (slomo && !mainmenu)
476 multiplier *= slomospeed;
477 oldmult = multiplier;
478 multiplier /= (float)count;
484 for (int i = 0; i < count; i++) {
487 multiplier = oldmult;
490 /* - Debug code to test how many channels were active on average per frame
491 static long frames = 0;
493 static AbsoluteTime start = {0,0};
494 AbsoluteTime currTime = UpTime ();
495 static int num_channels = 0;
497 num_channels += OPENAL_GetChannelsPlaying();
498 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
500 if (0 > deltaTime) // if negative microseconds
501 deltaTime /= -1000000.0;
502 else // else milliseconds
510 float avg_channels = (float)num_channels / (float)frames;
512 ofstream opstream("log.txt",ios::app);
513 opstream << "Average frame count: ";
515 opstream << " frames - ";
516 opstream << avg_channels;
517 opstream << " per frame.\n";
524 if ( stereomode == stereoNone ) {
525 DrawGLScene(stereoCenter);
527 DrawGLScene(stereoLeft);
528 DrawGLScene(stereoRight);
532 // --------------------------------------------------------------------------
540 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
541 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
544 // cheat here...static destructors are calling glDeleteTexture() after
545 // the context is destroyed and libGL unloaded by SDL_Quit().
546 pglDeleteTextures = glDeleteTextures_doNothing;
547 #endif // __MINGW32__
551 // --------------------------------------------------------------------------
553 static bool IsFocused()
555 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
561 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
562 static char *findBinaryInPath(const char *bin, char *envr)
564 size_t alloc_size = 0;
571 ptr = strchr(start, ':'); /* find next $PATH separator. */
575 size = strlen(start) + strlen(bin) + 2;
576 if (size > alloc_size) {
577 char *x = (char *) realloc(exe, size);
588 /* build full binary path... */
590 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
594 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
595 strcpy(exe, start); /* i'm lazy. piss off. */
599 start = ptr + 1; /* start points to beginning of next element. */
600 } while (ptr != NULL);
605 return(NULL); /* doesn't exist in path. */
606 } /* findBinaryInPath */
609 char *calcBaseDir(const char *argv0)
611 /* If there isn't a path on argv0, then look through the $PATH for it. */
615 if (strchr(argv0, '/')) {
616 retval = strdup(argv0);
618 *((char *) strrchr(retval, '/')) = '\0';
622 envr = getenv("PATH");
628 retval = findBinaryInPath(argv0, envr);
633 static inline void chdirToAppPath(const char *argv0)
635 char *dir = calcBaseDir(argv0);
637 #if (defined(__APPLE__) && defined(__MACH__))
638 // Chop off /Contents/MacOS if it's at the end of the string, so we
639 // land in the base of the app bundle.
640 const size_t len = strlen(dir);
641 const char *bundledirs = "/Contents/MacOS";
642 const size_t bundledirslen = strlen(bundledirs);
643 if (len > bundledirslen) {
644 char *ptr = (dir + len) - bundledirslen;
645 if (strcasecmp(ptr, bundledirs) == 0)
656 int main(int argc, char **argv)
661 // !!! FIXME: we could use a Win32 API for this. --ryan.
663 chdirToAppPath(argv[0]);
675 bool gameDone = false;
676 bool gameFocused = true;
678 while (!gameDone && !tryquit) {
682 // check windows messages
689 while ( SDL_PollEvent( &e ) ) {
690 if (!sdlEventProc(e)) {
701 // allow game chance to pause
706 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
717 } catch (const std::exception& error) {
720 std::string e = "Caught exception: ";
725 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);