2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "supertux/main.hpp"
22 #include <SDL_image.h>
26 #include <tinygettext/log.hpp>
29 namespace supertux_apple {
30 # include <CoreFoundation/CoreFoundation.h>
31 } // namespace supertux_apple
34 #include "addon/addon_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "control/joystickkeyboardcontroller.hpp"
37 #include "math/random_generator.hpp"
38 #include "physfs/ifile_stream.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "physfs/physfs_file_system.hpp"
41 #include "scripting/squirrel_util.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/screen_manager.hpp"
45 #include "supertux/resources.hpp"
46 #include "supertux/title_screen.hpp"
47 #include "util/file_system.hpp"
48 #include "util/gettext.hpp"
49 #include "video/drawing_context.hpp"
50 #include "worldmap/worldmap.hpp"
52 namespace { DrawingContext *context_pointer; }
57 g_config = new Config();
60 } catch(std::exception& e) {
61 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
66 Main::init_tinygettext()
68 dictionary_manager = new tinygettext::DictionaryManager();
69 tinygettext::Log::set_log_info_callback(0);
70 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
72 dictionary_manager->add_directory("locale");
73 dictionary_manager->set_charset("UTF-8");
75 // Config setting "locale" overrides language detection
76 if (g_config->locale != "")
78 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
83 Main::init_physfs(const char* argv0)
85 if(!PHYSFS_init(argv0)) {
86 std::stringstream msg;
87 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
88 throw std::runtime_error(msg.str());
91 // allow symbolic links
92 PHYSFS_permitSymbolicLinks(1);
94 // Initialize physfs (this is a slightly modified version of
95 // PHYSFS_setSaneConfig
96 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
97 const char* userdir = PHYSFS_getUserDir();
98 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
100 // Set configuration directory
101 sprintf(writedir, "%s.%s", userdir, application);
102 if(!PHYSFS_setWriteDir(writedir)) {
103 // try to create the directory
104 char* mkdir = new char[strlen(application) + 2];
105 sprintf(mkdir, ".%s", application);
106 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
107 std::ostringstream msg;
108 msg << "Failed creating configuration directory '"
109 << writedir << "': " << PHYSFS_getLastError();
112 throw std::runtime_error(msg.str());
116 if(!PHYSFS_setWriteDir(writedir)) {
117 std::ostringstream msg;
118 msg << "Failed to use configuration directory '"
119 << writedir << "': " << PHYSFS_getLastError();
121 throw std::runtime_error(msg.str());
124 PHYSFS_addToSearchPath(writedir, 0);
127 // when started from source dir...
128 std::string dir = PHYSFS_getBaseDir();
130 std::string testfname = dir;
131 testfname += "/credits.txt";
132 bool sourcedir = false;
133 FILE* f = fopen(testfname.c_str(), "r");
136 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
137 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
145 using namespace supertux_apple;
147 // when started from Application file on Mac OS X...
149 CFBundleRef mainBundle = CFBundleGetMainBundle();
150 assert(mainBundle != 0);
151 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
152 assert(mainBundleURL != 0);
153 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
154 assert(pathStr != 0);
155 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
156 CFRelease(mainBundleURL);
159 dir = std::string(path) + "/Contents/Resources/data";
160 testfname = dir + "/credits.txt";
162 f = fopen(testfname.c_str(), "r");
165 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
166 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
175 PHYSFS_addToSearchPath(".\\data", 1);
179 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
181 #ifdef ENABLE_BINRELOC
185 dir = br_find_data_dir(APPDATADIR);
190 datadir = APPDATADIR;
192 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
193 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
199 char** searchpath = PHYSFS_getSearchPath();
200 for(char** i = searchpath; *i != NULL; i++)
201 log_info << "[" << *i << "] is in the search path" << std::endl;
202 PHYSFS_freeList(searchpath);
206 Main::print_usage(const char* argv0)
208 std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
210 " -f, --fullscreen Run in fullscreen mode\n"
211 " -w, --window Run in window mode\n"
212 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
213 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
214 " -d, --default Reset video settings to default values\n"
215 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
216 " --disable-sfx Disable sound effects\n"
217 " --disable-music Disable music\n"
218 " -h, --help Show this help message and quit\n"
219 " -v, --version Show SuperTux version and quit\n"
220 " --console Enable ingame scripting console\n"
221 " --noconsole Disable ingame scripting console\n"
222 " --show-fps Display framerate in levels\n"
223 " --no-show-fps Do not display framerate in levels\n"
224 " --record-demo FILE LEVEL Record a demo to FILE\n"
225 " --play-demo FILE LEVEL Play a recorded demo\n"
226 " -s, --debug-scripts Enable script debugger.\n"
232 * Options that should be evaluated prior to any initializations at all go here
235 Main::pre_parse_commandline(int argc, char** argv)
237 for(int i = 1; i < argc; ++i) {
238 std::string arg = argv[i];
240 if(arg == "--version" || arg == "-v") {
241 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
244 if(arg == "--help" || arg == "-h") {
245 print_usage(argv[0]);
254 * Options that should be evaluated after config is read go here
257 Main::parse_commandline(int argc, char** argv)
259 for(int i = 1; i < argc; ++i) {
260 std::string arg = argv[i];
262 if(arg == "--fullscreen" || arg == "-f") {
263 g_config->use_fullscreen = true;
264 } else if(arg == "--default" || arg == "-d") {
265 g_config->use_fullscreen = false;
267 g_config->window_size = Size(800, 600);
268 g_config->fullscreen_size = Size(800, 600);
269 g_config->aspect_size = Size(0, 0); // auto detect
271 } else if(arg == "--window" || arg == "-w") {
272 g_config->use_fullscreen = false;
273 } else if(arg == "--geometry" || arg == "-g") {
277 print_usage(argv[0]);
278 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
283 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
285 print_usage(argv[0]);
286 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
290 g_config->window_size = Size(width, height);
291 g_config->fullscreen_size = Size(width, height);
294 } else if(arg == "--aspect" || arg == "-a") {
298 print_usage(argv[0]);
299 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
303 int aspect_width = 0;
304 int aspect_height = 0;
305 if (strcmp(argv[i], "auto") == 0)
310 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
312 print_usage(argv[0]);
313 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
317 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
319 // use aspect ratio to calculate logical resolution
320 if (aspect_ratio > 1) {
321 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
324 g_config->aspect_size = Size(600,
325 static_cast<int>(600 * 1/aspect_ratio + 0.5));
329 } else if(arg == "--renderer") {
333 print_usage(argv[0]);
334 throw std::runtime_error("Need to specify a renderer for renderer argument");
338 g_config->video = get_video_system(argv[i]);
340 } else if(arg == "--show-fps") {
341 g_config->show_fps = true;
342 } else if(arg == "--no-show-fps") {
343 g_config->show_fps = false;
344 } else if(arg == "--console") {
345 g_config->console_enabled = true;
346 } else if(arg == "--noconsole") {
347 g_config->console_enabled = false;
348 } else if(arg == "--disable-sfx") {
349 g_config->sound_enabled = false;
350 } else if(arg == "--disable-music") {
351 g_config->music_enabled = false;
352 } else if(arg == "--play-demo") {
354 print_usage(argv[0]);
355 throw std::runtime_error("Need to specify a demo filename");
357 g_config->start_demo = argv[++i];
358 } else if(arg == "--record-demo") {
360 print_usage(argv[0]);
361 throw std::runtime_error("Need to specify a demo filename");
363 g_config->record_demo = argv[++i];
364 } else if(arg == "--debug-scripts" || arg == "-s") {
365 g_config->enable_script_debugger = true;
366 } else if(arg[0] != '-') {
367 g_config->start_level = arg;
369 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
380 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
381 std::stringstream msg;
382 msg << "Couldn't initialize SDL: " << SDL_GetError();
383 throw std::runtime_error(msg.str());
388 SDL_EnableUNICODE(1);
390 // wait 100ms and clear SDL event queue because sometimes we have random
391 // joystick events in the queue on startup...
394 while(SDL_PollEvent(&dummy))
401 g_config->random_seed = systemRandom.srand(g_config->random_seed);
403 //const char *how = config->random_seed? ", user fixed.": ", from time().";
404 //log_info << "Using random seed " << config->random_seed << how << std::endl;
410 // FIXME: Add something here
414 context_pointer->init_renderer();
415 g_screen = SDL_GetVideoSurface();
417 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
421 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
423 const char* icon_fname = "images/engine/icons/supertux.xpm";
427 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
428 } catch (const std::runtime_error& err) {
430 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
433 SDL_WM_SetIcon(icon, 0);
434 SDL_FreeSurface(icon);
438 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
444 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
445 << " Window: " << g_config->window_size
446 << " Fullscreen: " << g_config->fullscreen_size
447 << " Area: " << g_config->aspect_size << std::endl;
453 sound_manager = new SoundManager();
455 sound_manager->enable_sound(g_config->sound_enabled);
456 sound_manager->enable_music(g_config->music_enabled);
462 if(sound_manager != NULL) {
463 delete sound_manager;
464 sound_manager = NULL;
469 Main::wait_for_event(float min_delay, float max_delay)
471 assert(min_delay <= max_delay);
473 Uint32 min = (Uint32) (min_delay * 1000);
474 Uint32 max = (Uint32) (max_delay * 1000);
476 Uint32 ticks = SDL_GetTicks();
477 while(SDL_GetTicks() - ticks < min) {
479 sound_manager->update();
484 while (SDL_PollEvent(&event))
488 bool running = false;
489 ticks = SDL_GetTicks();
491 while(SDL_PollEvent(&event)) {
494 g_screen_manager->quit();
497 case SDL_JOYBUTTONDOWN:
498 case SDL_MOUSEBUTTONDOWN:
502 if(SDL_GetTicks() - ticks >= (max - min))
504 sound_manager->update();
510 static Uint32 last_timelog_ticks = 0;
511 static const char* last_timelog_component = 0;
513 static inline void timelog(const char* component)
515 Uint32 current_ticks = SDL_GetTicks();
517 if(last_timelog_component != 0) {
518 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
521 last_timelog_ticks = current_ticks;
522 last_timelog_component = component;
525 static inline void timelog(const char* )
531 Main::main(int argc, char** argv)
537 if(pre_parse_commandline(argc, argv))
540 Console::instance = new Console();
541 init_physfs(argv[0]);
544 timelog("controller");
545 g_main_controller = new JoystickKeyboardController();
551 AddonManager::get_instance().load_addons();
553 timelog("tinygettext");
556 timelog("commandline");
557 if(parse_commandline(argc, argv))
564 DrawingContext context;
565 context_pointer = &context;
568 Console::instance->init_graphics();
570 timelog("scripting");
571 scripting::init_squirrel(g_config->enable_script_debugger);
573 timelog("resources");
574 Resources::load_shared();
578 g_screen_manager = new ScreenManager();
579 if(g_config->start_level != "") {
580 // we have a normal path specified at commandline, not a physfs path.
581 // So we simply mount that path here...
582 std::string dir = FileSystem::dirname(g_config->start_level);
583 log_debug << "Adding dir: " << dir << std::endl;
584 PHYSFS_addToSearchPath(dir.c_str(), true);
586 if(g_config->start_level.size() > 4 &&
587 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
589 g_screen_manager->push_screen(new worldmap::WorldMap(
590 FileSystem::basename(g_config->start_level)));
592 init_rand();//If level uses random eg. for
593 // rain particles before we do this:
594 std::auto_ptr<GameSession> session (
595 new GameSession(FileSystem::basename(g_config->start_level)));
597 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
598 init_rand();//initialise generator with seed from session
600 if(g_config->start_demo != "")
601 session->play_demo(g_config->start_demo);
603 if(g_config->record_demo != "")
604 session->record_demo(g_config->record_demo);
605 g_screen_manager->push_screen(session.release());
609 g_screen_manager->push_screen(new TitleScreen());
612 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
613 g_screen_manager->run(context);
614 } catch(std::exception& e) {
615 log_fatal << "Unexpected exception: " << e.what() << std::endl;
618 log_fatal << "Unexpected exception" << std::endl;
622 delete g_screen_manager;
623 g_screen_manager = NULL;
625 Resources::unload_shared();
632 delete g_main_controller;
633 g_main_controller = NULL;
634 delete Console::instance;
635 Console::instance = NULL;
636 scripting::exit_squirrel();
637 delete texture_manager;
638 texture_manager = NULL;