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/>.
29 #include "openal_wrapper.h"
31 extern float multiplier;
33 extern float realmultiplier;
35 extern bool cellophane;
36 extern float texdetail;
40 extern bool stillloading;
45 extern float slomospeed;
46 extern float slomofreq;
47 extern bool visibleloading;
59 #include "MacCompatibility.h"
64 #include "win-res/resource.h"
67 extern SDL_Window *sdlwindow;
71 set<pair<int,int>> resolutions;
78 // statics/globals (internal only) ------------------------------------------
82 #pragma warning(disable: 4273)
85 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
86 #define GL_FUNC(ret,fn,params,call,rt) \
88 static ret (GLAPIENTRY *p##fn) params = NULL; \
89 ret GLAPIENTRY fn params { rt p##fn call; } \
99 static bool lookup_glsym(const char *funcname, void **func)
101 *func = SDL_GL_GetProcAddress(funcname);
103 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
109 static bool lookup_all_glsyms(void)
112 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
113 #define GL_FUNC(ret,fn,params,call,rt) \
114 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
117 #endif // __MINGW32__
121 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
122 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
126 #endif // __MINGW32__
131 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
138 Boolean gDone = false;
140 static int _argc = 0;
141 static char **_argv = NULL;
143 bool cmdline(const char *cmd)
145 for (int i = 1; i < _argc; i++) {
146 char *arg = _argv[i];
149 if (strcasecmp(arg, cmd) == 0)
156 //-----------------------------------------------------------------------------------------------------------------------
162 glClear( GL_COLOR_BUFFER_BIT );
166 glDisable( GL_ALPHA_TEST);
167 glDisable( GL_BLEND);
168 glDisable( GL_DEPTH_TEST);
170 glDisable( GL_LIGHTING);
171 glDisable( GL_LOGIC_OP);
172 glDisable( GL_TEXTURE_1D);
173 glDisable( GL_TEXTURE_2D);
174 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
175 glPixelTransferi( GL_RED_SCALE, 1);
176 glPixelTransferi( GL_RED_BIAS, 0);
177 glPixelTransferi( GL_GREEN_SCALE, 1);
178 glPixelTransferi( GL_GREEN_BIAS, 0);
179 glPixelTransferi( GL_BLUE_SCALE, 1);
180 glPixelTransferi( GL_BLUE_BIAS, 0);
181 glPixelTransferi( GL_ALPHA_SCALE, 1);
182 glPixelTransferi( GL_ALPHA_BIAS, 0);
184 // set initial rendering states
185 glShadeModel( GL_SMOOTH);
187 glDepthFunc( GL_LEQUAL);
188 glDepthMask( GL_TRUE);
189 glEnable( GL_DEPTH_TEST);
190 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
191 glCullFace( GL_FRONT);
192 glEnable( GL_CULL_FACE);
193 glEnable( GL_LIGHTING);
194 glEnable( GL_DITHER);
195 glEnable( GL_COLOR_MATERIAL);
196 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
197 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
198 glAlphaFunc( GL_GREATER, 0.5f);
200 if ( CanInitStereo(stereomode) ) {
201 InitStereo(stereomode);
203 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
204 stereomode = stereoNone;
208 void toggleFullscreen()
210 fullscreen = !fullscreen;
211 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
212 if (flags & SDL_WINDOW_FULLSCREEN) {
213 flags &= ~SDL_WINDOW_FULLSCREEN;
215 flags |= SDL_WINDOW_FULLSCREEN;
217 SDL_SetWindowFullscreen(sdlwindow, flags);
220 static SDL_bool sdlEventProc(const SDL_Event &e)
226 case SDL_WINDOWEVENT:
227 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
232 case SDL_MOUSEMOTION:
233 deltah += e.motion.xrel;
234 deltav += e.motion.yrel;
238 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
239 (e.key.keysym.mod & KMOD_CTRL)) {
240 SDL_bool mode = SDL_TRUE;
241 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
242 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
243 SDL_SetWindowGrab(sdlwindow, mode);
244 SDL_SetRelativeMouseMode(mode);
245 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
255 // --------------------------------------------------------------------------
257 static Point gMidPoint;
271 if (!SDL_WasInit(SDL_INIT_VIDEO))
272 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
273 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
276 if (!LoadSettings()) {
277 fprintf(stderr, "Failed to load config, creating default\n");
280 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
284 if (SDL_GL_LoadLibrary(NULL) == -1) {
285 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
290 for (int displayIdx = 0; displayIdx < SDL_GetNumVideoDisplays(); ++displayIdx) {
291 for (int i = 0; i < SDL_GetNumDisplayModes(displayIdx); ++i) {
292 SDL_DisplayMode mode;
293 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
295 if ((mode.w < 640) || (mode.h < 480))
296 continue; // sane lower limit.
297 pair<int,int> resolution(mode.w, mode.h);
298 resolutions.insert(resolution);
302 if (resolutions.empty()) {
303 const std::string error = "No suitable video resolutions found.";
304 cerr << error << endl;
305 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
310 if (cmdline("showresolutions")) {
311 printf("Available resolutions:\n");
312 for (auto resolution = resolutions.begin(); resolution != resolutions.end(); resolution++) {
313 printf(" %d x %d\n", (int) resolution->first, (int) resolution->second);
317 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
318 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
320 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
321 if ((fullscreen || cmdline("fullscreen")) && !cmdline("windowed")) {
323 sdlflags |= SDL_WINDOW_FULLSCREEN;
325 if (!cmdline("nomousegrab"))
326 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
328 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
329 kContextWidth, kContextHeight, sdlflags);
332 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
333 fprintf(stderr, "forcing 640x480...\n");
335 kContextHeight = 480;
336 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
337 kContextWidth, kContextHeight, sdlflags);
339 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
340 fprintf(stderr, "forcing 640x480 windowed mode...\n");
341 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
342 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0),
343 kContextWidth, kContextHeight, sdlflags);
346 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
352 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
354 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
359 SDL_GL_MakeCurrent(sdlwindow, glctx);
361 if (!lookup_all_glsyms()) {
362 fprintf(stderr, "Missing required OpenGL functions.\n");
368 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
370 fprintf(stderr, "Failed to get a double-buffered context.\n");
375 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
376 SDL_GL_SetSwapInterval(1);
379 if (!cmdline("nomousegrab"))
380 SDL_SetRelativeMouseMode(SDL_TRUE);
384 GLint width = kContextWidth;
385 GLint height = kContextHeight;
386 gMidPoint.h = width / 2;
387 gMidPoint.v = height / 2;
389 screenheight = height;
392 newscreenwidth = screenwidth;
393 newscreenheight = screenheight;
395 /* If saved resolution is not in the list, add it to the list (so that it’s selectable in the options) */
396 pair<int,int> startresolution(width,height);
397 if (resolutions.find(startresolution) == resolutions.end()) {
398 resolutions.insert(startresolution);
407 static void DoMouse()
410 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
411 deltah *= usermousesensitivity;
412 deltav *= usermousesensitivity;
413 mousecoordh += deltah;
414 mousecoordv += deltav;
417 else if (mousecoordh >= kContextWidth)
418 mousecoordh = kContextWidth - 1;
421 else if (mousecoordv >= kContextHeight)
422 mousecoordv = kContextHeight - 1;
427 void DoFrameRate (int update)
429 static long frames = 0;
431 static AbsoluteTime time = {0, 0};
432 static AbsoluteTime frametime = {0, 0};
433 AbsoluteTime currTime = UpTime ();
434 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
436 if (0 > deltaTime) // if negative microseconds
437 deltaTime /= -1000000.0;
438 else // else milliseconds
441 multiplier = deltaTime;
442 if (multiplier < .001)
447 frametime = currTime; // reset for next time interval
449 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
451 if (0 > deltaTime) // if negative microseconds
452 deltaTime /= -1000000.0;
453 else // else milliseconds
456 if (0.001 <= deltaTime) { // has update interval passed
458 time = currTime; // reset for next time interval
467 static float sps = 200;
469 static float oldmult;
475 fps = 1 / multiplier;
477 count = multiplier * sps;
481 realmultiplier = multiplier;
482 multiplier *= gamespeed;
489 multiplier *= .00001;
490 if (slomo && !mainmenu)
491 multiplier *= slomospeed;
492 oldmult = multiplier;
493 multiplier /= (float)count;
499 for (int i = 0; i < count; i++) {
502 multiplier = oldmult;
505 /* - Debug code to test how many channels were active on average per frame
506 static long frames = 0;
508 static AbsoluteTime start = {0,0};
509 AbsoluteTime currTime = UpTime ();
510 static int num_channels = 0;
512 num_channels += OPENAL_GetChannelsPlaying();
513 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
515 if (0 > deltaTime) // if negative microseconds
516 deltaTime /= -1000000.0;
517 else // else milliseconds
525 float avg_channels = (float)num_channels / (float)frames;
527 ofstream opstream("log.txt",ios::app);
528 opstream << "Average frame count: ";
530 opstream << " frames - ";
531 opstream << avg_channels;
532 opstream << " per frame.\n";
539 if ( stereomode == stereoNone ) {
540 DrawGLScene(stereoCenter);
542 DrawGLScene(stereoLeft);
543 DrawGLScene(stereoRight);
547 // --------------------------------------------------------------------------
555 #ifndef __MINGW32__ // FIXME: Temporary workaround for GL-8
556 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
559 // cheat here...static destructors are calling glDeleteTexture() after
560 // the context is destroyed and libGL unloaded by SDL_Quit().
561 pglDeleteTextures = glDeleteTextures_doNothing;
562 #endif // __MINGW32__
566 // --------------------------------------------------------------------------
568 static bool IsFocused()
570 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
576 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
577 static char *findBinaryInPath(const char *bin, char *envr)
579 size_t alloc_size = 0;
586 ptr = strchr(start, ':'); /* find next $PATH separator. */
590 size = strlen(start) + strlen(bin) + 2;
591 if (size > alloc_size) {
592 char *x = (char *) realloc(exe, size);
603 /* build full binary path... */
605 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
609 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
610 strcpy(exe, start); /* i'm lazy. piss off. */
614 start = ptr + 1; /* start points to beginning of next element. */
615 } while (ptr != NULL);
620 return(NULL); /* doesn't exist in path. */
621 } /* findBinaryInPath */
624 char *calcBaseDir(const char *argv0)
626 /* If there isn't a path on argv0, then look through the $PATH for it. */
630 if (strchr(argv0, '/')) {
631 retval = strdup(argv0);
633 *((char *) strrchr(retval, '/')) = '\0';
637 envr = getenv("PATH");
643 retval = findBinaryInPath(argv0, envr);
648 static inline void chdirToAppPath(const char *argv0)
650 char *dir = calcBaseDir(argv0);
652 #if (defined(__APPLE__) && defined(__MACH__))
653 // Chop off /Contents/MacOS if it's at the end of the string, so we
654 // land in the base of the app bundle.
655 const size_t len = strlen(dir);
656 const char *bundledirs = "/Contents/MacOS";
657 const size_t bundledirslen = strlen(bundledirs);
658 if (len > bundledirslen) {
659 char *ptr = (dir + len) - bundledirslen;
660 if (strcasecmp(ptr, bundledirs) == 0)
671 int main(int argc, char **argv)
676 // !!! FIXME: we could use a Win32 API for this. --ryan.
678 chdirToAppPath(argv[0]);
687 //ofstream os("error.txt");
689 //ofstream os("log.txt");
695 while (!gDone && !tryquit) {
699 // check windows messages
706 while ( SDL_PollEvent( &e ) ) {
707 if (!sdlEventProc(e)) {
718 // allow game chance to pause
723 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
734 } catch (const std::exception& error) {
737 std::string e = "Caught exception: ";
742 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);