4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program 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 this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
31 #include <sys/types.h>
35 #include <SDL_image.h>
37 #include "gameconfig.hpp"
38 #include "resources.hpp"
39 #include "gettext.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "video/surface.hpp"
42 #include "video/texture_manager.hpp"
43 #include "video/drawing_context.hpp"
44 #include "video/glutil.hpp"
45 #include "control/joystickkeyboardcontroller.hpp"
46 #include "options_menu.hpp"
47 #include "mainloop.hpp"
49 #include "game_session.hpp"
50 #include "scripting/level.hpp"
51 #include "scripting/squirrel_util.hpp"
52 #include "file_system.hpp"
53 #include "physfs/physfs_sdl.hpp"
54 #include "random_generator.hpp"
55 #include "worldmap/worldmap.hpp"
56 #include "binreloc/binreloc.h"
58 namespace { DrawingContext *context_pointer; }
60 JoystickKeyboardController* main_controller = 0;
61 TinyGetText::DictionaryManager dictionary_manager;
66 static void init_config()
68 config = new Config();
71 } catch(std::exception& e) {
72 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
76 static void init_tinygettext()
78 dictionary_manager.add_directory("locale");
79 dictionary_manager.set_charset("UTF-8");
81 // Config setting "locale" overrides language detection
82 if (config->locale != "") {
83 dictionary_manager.set_language( config->locale );
87 static void init_physfs(const char* argv0)
89 if(!PHYSFS_init(argv0)) {
90 std::stringstream msg;
91 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
92 throw std::runtime_error(msg.str());
95 // Initialize physfs (this is a slightly modified version of
96 // PHYSFS_setSaneConfig
97 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
98 const char* userdir = PHYSFS_getUserDir();
99 const char* dirsep = PHYSFS_getDirSeparator();
100 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
102 // Set configuration directory
103 sprintf(writedir, "%s.%s", userdir, application);
104 if(!PHYSFS_setWriteDir(writedir)) {
105 // try to create the directory
106 char* mkdir = new char[strlen(application) + 2];
107 sprintf(mkdir, ".%s", application);
108 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
109 std::ostringstream msg;
110 msg << "Failed creating configuration directory '"
111 << writedir << "': " << PHYSFS_getLastError();
114 throw std::runtime_error(msg.str());
118 if(!PHYSFS_setWriteDir(writedir)) {
119 std::ostringstream msg;
120 msg << "Failed to use configuration directory '"
121 << writedir << "': " << PHYSFS_getLastError();
123 throw std::runtime_error(msg.str());
126 PHYSFS_addToSearchPath(writedir, 0);
129 // Search for archives and add them to the search path
130 const char* archiveExt = "zip";
131 char** rc = PHYSFS_enumerateFiles("/");
132 size_t extlen = strlen(archiveExt);
134 for(char** i = rc; *i != 0; ++i) {
135 size_t l = strlen(*i);
136 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
137 const char* ext = (*i) + (l - extlen);
138 if(strcasecmp(ext, archiveExt) == 0) {
139 const char* d = PHYSFS_getRealDir(*i);
140 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
141 sprintf(str, "%s%s%s", d, dirsep, *i);
142 PHYSFS_addToSearchPath(str, 1);
150 // when started from source dir...
151 std::string dir = PHYSFS_getBaseDir();
153 std::string testfname = dir;
154 testfname += "/credits.txt";
155 bool sourcedir = false;
156 FILE* f = fopen(testfname.c_str(), "r");
159 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
160 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167 // when started from Application file on Mac OS X...
168 dir = PHYSFS_getBaseDir();
169 dir += "SuperTux.app/Contents/Resources/data";
170 testfname = dir + "/credits.txt";
172 f = fopen(testfname.c_str(), "r");
175 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
176 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
184 PHYSFS_addToSearchPath(".\\data", 1);
188 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
190 #ifdef ENABLE_BINRELOC
194 dir = br_find_data_dir(APPDATADIR);
199 datadir = APPDATADIR;
202 datadir += application;
203 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
204 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
209 // allow symbolic links
210 PHYSFS_permitSymbolicLinks(1);
213 char** searchpath = PHYSFS_getSearchPath();
214 for(char** i = searchpath; *i != NULL; i++)
215 log_info << "[" << *i << "] is in the search path" << std::endl;
216 PHYSFS_freeList(searchpath);
219 static void print_usage(const char* argv0)
221 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
224 " -f, --fullscreen Run in fullscreen mode\n"
225 " -w, --window Run in window mode\n"
226 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
227 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
228 " --disable-sfx Disable sound effects\n"
229 " --disable-music Disable music\n"
230 " --help Show this help message\n"
231 " --version Display SuperTux version and quit\n"
232 " --console Enable ingame scripting console\n"
233 " --noconsole Disable ingame scripting console\n"
234 " --show-fps Display framerate in levels\n"
235 " --no-show-fps Do not display framerate in levels\n"
236 " --record-demo FILE LEVEL Record a demo to FILE\n"
237 " --play-demo FILE LEVEL Play a recorded demo\n"
242 * Options that should be evaluated prior to any initializations at all go here
244 static bool pre_parse_commandline(int argc, char** argv)
246 for(int i = 1; i < argc; ++i) {
247 std::string arg = argv[i];
249 if(arg == "--version") {
250 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
259 * Options that should be evaluated after config is read go here
261 static bool parse_commandline(int argc, char** argv)
263 for(int i = 1; i < argc; ++i) {
264 std::string arg = argv[i];
266 if(arg == "--help") {
267 print_usage(argv[0]);
269 } else if(arg == "--fullscreen" || arg == "-f") {
270 config->use_fullscreen = true;
271 } else if(arg == "--window" || arg == "-w") {
272 config->use_fullscreen = false;
273 } else if(arg == "--geometry" || arg == "-g") {
275 print_usage(argv[0]);
276 throw std::runtime_error("Need to specify a parameter for geometry switch");
278 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
280 print_usage(argv[0]);
281 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
283 } else if(arg == "--aspect" || arg == "-a") {
285 print_usage(argv[0]);
286 throw std::runtime_error("Need to specify a parameter for aspect switch");
288 if(strcasecmp(argv[i+1], "auto") == 0) {
290 config->aspect_ratio = -1;
292 int aspect_width, aspect_height;
293 if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
294 print_usage(argv[0]);
295 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
297 config->aspect_ratio = static_cast<double>(aspect_width) /
298 static_cast<double>(aspect_height);
300 } else if(arg == "--show-fps") {
301 config->show_fps = true;
302 } else if(arg == "--no-show-fps") {
303 config->show_fps = false;
304 } else if(arg == "--console") {
305 config->console_enabled = true;
306 } else if(arg == "--noconsole") {
307 config->console_enabled = false;
308 } else if(arg == "--disable-sfx") {
309 config->sound_enabled = false;
310 } else if(arg == "--disable-music") {
311 config->music_enabled = false;
312 } else if(arg == "--play-demo") {
314 print_usage(argv[0]);
315 throw std::runtime_error("Need to specify a demo filename");
317 config->start_demo = argv[++i];
318 } else if(arg == "--record-demo") {
320 print_usage(argv[0]);
321 throw std::runtime_error("Need to specify a demo filename");
323 config->record_demo = argv[++i];
324 } else if(arg == "-d") {
325 config->enable_script_debugger = true;
326 } else if(arg[0] != '-') {
327 config->start_level = arg;
329 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
337 static void init_sdl()
339 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
340 std::stringstream msg;
341 msg << "Couldn't initialize SDL: " << SDL_GetError();
342 throw std::runtime_error(msg.str());
347 SDL_EnableUNICODE(1);
349 // wait 100ms and clear SDL event queue because sometimes we have random
350 // joystick events in the queue on startup...
353 while(SDL_PollEvent(&dummy))
357 static void init_rand()
359 config->random_seed = systemRandom.srand(config->random_seed);
361 //const char *how = config->random_seed? ", user fixed.": ", from time().";
362 //log_info << "Using random seed " << config->random_seed << how << std::endl;
367 static int desktop_width = 0;
368 static int desktop_height = 0;
370 /* unfortunately only newer SDLs have these infos */
371 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
372 /* find which resolution the user normally uses */
373 if(desktop_width == 0) {
374 const SDL_VideoInfo *info = SDL_GetVideoInfo();
375 desktop_width = info->current_w;
376 desktop_height = info->current_h;
380 double aspect_ratio = config->aspect_ratio;
382 // try to guess aspect ratio of monitor if needed
383 if (aspect_ratio <= 0) {
384 if(config->use_fullscreen && desktop_width > 0) {
385 aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
387 aspect_ratio = 4.0 / 3.0;
391 // use aspect ratio to calculate logical resolution
392 if (aspect_ratio > 1) {
393 SCREEN_WIDTH = static_cast<int> (600 * aspect_ratio + 0.5);
397 SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
400 context_pointer->init_renderer();
401 screen = SDL_GetVideoSurface();
403 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
406 SDL_Surface* icon = IMG_Load_RW(
407 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
409 SDL_WM_SetIcon(icon, 0);
410 SDL_FreeSurface(icon);
414 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
420 log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
423 static void init_audio()
425 sound_manager = new SoundManager();
427 sound_manager->enable_sound(config->sound_enabled);
428 sound_manager->enable_music(config->music_enabled);
431 static void quit_audio()
433 if(sound_manager != NULL) {
434 delete sound_manager;
435 sound_manager = NULL;
439 void wait_for_event(float min_delay, float max_delay)
441 assert(min_delay <= max_delay);
443 Uint32 min = (Uint32) (min_delay * 1000);
444 Uint32 max = (Uint32) (max_delay * 1000);
446 Uint32 ticks = SDL_GetTicks();
447 while(SDL_GetTicks() - ticks < min) {
449 sound_manager->update();
454 while (SDL_PollEvent(&event))
458 bool running = false;
459 ticks = SDL_GetTicks();
461 while(SDL_PollEvent(&event)) {
467 case SDL_JOYBUTTONDOWN:
468 case SDL_MOUSEBUTTONDOWN:
472 if(SDL_GetTicks() - ticks >= (max - min))
474 sound_manager->update();
480 static Uint32 last_timelog_ticks = 0;
481 static const char* last_timelog_component = 0;
483 static inline void timelog(const char* component)
485 Uint32 current_ticks = SDL_GetTicks();
487 if(last_timelog_component != 0) {
488 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
491 last_timelog_ticks = current_ticks;
492 last_timelog_component = component;
495 static inline void timelog(const char* )
500 int main(int argc, char** argv)
508 if(pre_parse_commandline(argc, argv))
511 Console::instance = new Console();
512 init_physfs(argv[0]);
515 timelog("controller");
516 main_controller = new JoystickKeyboardController();
519 timelog("tinygettext");
521 timelog("commandline");
522 if(parse_commandline(argc, argv))
527 DrawingContext context;
528 context_pointer = &context;
530 Console::instance->init_graphics();
531 timelog("scripting");
532 Scripting::init_squirrel(config->enable_script_debugger);
533 timelog("resources");
537 main_loop = new MainLoop();
538 if(config->start_level != "") {
539 // we have a normal path specified at commandline not physfs paths.
540 // So we simply mount that path here...
541 std::string dir = FileSystem::dirname(config->start_level);
542 PHYSFS_addToSearchPath(dir.c_str(), true);
544 if(config->start_level.size() > 4 &&
545 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
547 main_loop->push_screen(new WorldMapNS::WorldMap(
548 FileSystem::basename(config->start_level)));
550 init_rand();//If level uses random eg. for
551 // rain particles before we do this:
552 std::auto_ptr<GameSession> session (
553 new GameSession(FileSystem::basename(config->start_level)));
555 config->random_seed =session->get_demo_random_seed(config->start_demo);
556 init_rand();//initialise generator with seed from session
558 if(config->start_demo != "")
559 session->play_demo(config->start_demo);
561 if(config->record_demo != "")
562 session->record_demo(config->record_demo);
563 main_loop->push_screen(session.release());
567 main_loop->push_screen(new TitleScreen());
570 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
571 main_loop->run(context);
573 } catch(std::exception& e) {
574 log_fatal << "Unexpected exception: " << e.what() << std::endl;
577 log_fatal << "Unexpected exception" << std::endl;
593 delete main_controller;
594 main_controller = NULL;
595 delete Console::instance;
596 Console::instance = NULL;
597 Scripting::exit_squirrel();
598 delete texture_manager;
599 texture_manager = NULL;