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>
28 namespace supertux_apple {
29 # include <CoreFoundation/CoreFoundation.h>
30 } // namespace supertux_apple
33 #include "tinygettext/log.hpp"
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/joystickkeyboardcontroller.hpp"
38 #include "math/random_generator.hpp"
39 #include "physfs/ifile_stream.hpp"
40 #include "physfs/physfs_sdl.hpp"
41 #include "physfs/physfs_file_system.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/gameconfig.hpp"
44 #include "supertux/globals.hpp"
45 #include "supertux/screen_manager.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/title_screen.hpp"
48 #include "util/file_system.hpp"
49 #include "util/gettext.hpp"
50 #include "video/drawing_context.hpp"
51 #include "worldmap/worldmap.hpp"
53 namespace { DrawingContext *context_pointer; }
58 g_config = new Config();
61 } catch(std::exception& e) {
62 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
67 Main::init_tinygettext()
69 dictionary_manager = new tinygettext::DictionaryManager();
70 tinygettext::Log::set_log_info_callback(0);
71 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
73 dictionary_manager->add_directory("locale");
74 dictionary_manager->set_charset("UTF-8");
76 // Config setting "locale" overrides language detection
77 if (g_config->locale != "")
79 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
84 Main::init_physfs(const char* argv0)
86 if(!PHYSFS_init(argv0)) {
87 std::stringstream msg;
88 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
89 throw std::runtime_error(msg.str());
92 // allow symbolic links
93 PHYSFS_permitSymbolicLinks(1);
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 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
101 // Set configuration directory
102 sprintf(writedir, "%s.%s", userdir, application);
103 if(!PHYSFS_setWriteDir(writedir)) {
104 // try to create the directory
105 char* mkdir = new char[strlen(application) + 2];
106 sprintf(mkdir, ".%s", application);
107 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
108 std::ostringstream msg;
109 msg << "Failed creating configuration directory '"
110 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
117 if(!PHYSFS_setWriteDir(writedir)) {
118 std::ostringstream msg;
119 msg << "Failed to use configuration directory '"
120 << writedir << "': " << PHYSFS_getLastError();
122 throw std::runtime_error(msg.str());
125 PHYSFS_addToSearchPath(writedir, 0);
128 // when started from source dir...
129 std::string dir = PHYSFS_getBaseDir();
131 std::string testfname = dir;
132 testfname += "/credits.txt";
133 bool sourcedir = false;
134 FILE* f = fopen(testfname.c_str(), "r");
137 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
138 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
146 using namespace supertux_apple;
148 // when started from Application file on Mac OS X...
150 CFBundleRef mainBundle = CFBundleGetMainBundle();
151 assert(mainBundle != 0);
152 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
153 assert(mainBundleURL != 0);
154 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
155 assert(pathStr != 0);
156 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
157 CFRelease(mainBundleURL);
160 dir = std::string(path) + "/Contents/Resources/data";
161 testfname = dir + "/credits.txt";
163 f = fopen(testfname.c_str(), "r");
166 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
167 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
176 PHYSFS_addToSearchPath(".\\data", 1);
180 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
182 #ifdef ENABLE_BINRELOC
186 dir = br_find_data_dir(APPDATADIR);
191 datadir = APPDATADIR;
193 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
194 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
200 char** searchpath = PHYSFS_getSearchPath();
201 for(char** i = searchpath; *i != NULL; i++)
202 log_info << "[" << *i << "] is in the search path" << std::endl;
203 PHYSFS_freeList(searchpath);
207 Main::print_usage(const char* argv0)
209 std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
211 " -f, --fullscreen Run in fullscreen mode\n"
212 " -w, --window Run in window mode\n"
213 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
214 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
215 " -d, --default Reset video settings to default values\n"
216 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
217 " --disable-sfx Disable sound effects\n"
218 " --disable-music Disable music\n"
219 " -h, --help Show this help message and quit\n"
220 " -v, --version Show SuperTux version and quit\n"
221 " --console Enable ingame scripting console\n"
222 " --noconsole Disable ingame scripting console\n"
223 " --show-fps Display framerate in levels\n"
224 " --no-show-fps Do not display framerate in levels\n"
225 " --record-demo FILE LEVEL Record a demo to FILE\n"
226 " --play-demo FILE LEVEL Play a recorded demo\n"
227 " -s, --debug-scripts Enable script debugger.\n"
233 * Options that should be evaluated prior to any initializations at all go here
236 Main::pre_parse_commandline(int argc, char** argv)
238 for(int i = 1; i < argc; ++i) {
239 std::string arg = argv[i];
241 if(arg == "--version" || arg == "-v") {
242 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
245 if(arg == "--help" || arg == "-h") {
246 print_usage(argv[0]);
255 * Options that should be evaluated after config is read go here
258 Main::parse_commandline(int argc, char** argv)
260 for(int i = 1; i < argc; ++i) {
261 std::string arg = argv[i];
263 if(arg == "--fullscreen" || arg == "-f") {
264 g_config->use_fullscreen = true;
265 } else if(arg == "--default" || arg == "-d") {
266 g_config->use_fullscreen = false;
268 g_config->window_width = 800;
269 g_config->window_height = 600;
271 g_config->fullscreen_width = 800;
272 g_config->fullscreen_height = 600;
274 g_config->aspect_width = 0; // auto detect
275 g_config->aspect_height = 0;
277 } else if(arg == "--window" || arg == "-w") {
278 g_config->use_fullscreen = false;
279 } else if(arg == "--geometry" || arg == "-g") {
283 print_usage(argv[0]);
284 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
289 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
291 print_usage(argv[0]);
292 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
296 g_config->window_width = width;
297 g_config->window_height = height;
299 g_config->fullscreen_width = width;
300 g_config->fullscreen_height = height;
303 } else if(arg == "--aspect" || arg == "-a") {
307 print_usage(argv[0]);
308 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
312 int aspect_width = 0;
313 int aspect_height = 0;
314 if (strcmp(argv[i], "auto") == 0)
319 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
321 print_usage(argv[0]);
322 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
326 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
327 static_cast<double>(g_config->aspect_height);
329 // use aspect ratio to calculate logical resolution
330 if (aspect_ratio > 1) {
331 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
332 g_config->aspect_height = 600;
334 g_config->aspect_width = 600;
335 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
339 } else if(arg == "--renderer") {
343 print_usage(argv[0]);
344 throw std::runtime_error("Need to specify a renderer for renderer argument");
348 g_config->video = get_video_system(argv[i]);
350 } else if(arg == "--show-fps") {
351 g_config->show_fps = true;
352 } else if(arg == "--no-show-fps") {
353 g_config->show_fps = false;
354 } else if(arg == "--console") {
355 g_config->console_enabled = true;
356 } else if(arg == "--noconsole") {
357 g_config->console_enabled = false;
358 } else if(arg == "--disable-sfx") {
359 g_config->sound_enabled = false;
360 } else if(arg == "--disable-music") {
361 g_config->music_enabled = false;
362 } else if(arg == "--play-demo") {
364 print_usage(argv[0]);
365 throw std::runtime_error("Need to specify a demo filename");
367 g_config->start_demo = argv[++i];
368 } else if(arg == "--record-demo") {
370 print_usage(argv[0]);
371 throw std::runtime_error("Need to specify a demo filename");
373 g_config->record_demo = argv[++i];
374 } else if(arg == "--debug-scripts" || arg == "-s") {
375 g_config->enable_script_debugger = true;
376 } else if(arg[0] != '-') {
377 g_config->start_level = arg;
379 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
390 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
391 std::stringstream msg;
392 msg << "Couldn't initialize SDL: " << SDL_GetError();
393 throw std::runtime_error(msg.str());
398 SDL_EnableUNICODE(1);
400 // wait 100ms and clear SDL event queue because sometimes we have random
401 // joystick events in the queue on startup...
404 while(SDL_PollEvent(&dummy))
411 g_config->random_seed = systemRandom.srand(g_config->random_seed);
413 //const char *how = config->random_seed? ", user fixed.": ", from time().";
414 //log_info << "Using random seed " << config->random_seed << how << std::endl;
420 // FIXME: Add something here
424 context_pointer->init_renderer();
425 g_screen = SDL_GetVideoSurface();
427 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
431 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
433 const char* icon_fname = "images/engine/icons/supertux.xpm";
437 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
438 } catch (const std::runtime_error& err) {
440 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
443 SDL_WM_SetIcon(icon, 0);
444 SDL_FreeSurface(icon);
448 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
454 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
455 << " Window: " << g_config->window_width << "x" << g_config->window_height
456 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
457 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
463 sound_manager = new SoundManager();
465 sound_manager->enable_sound(g_config->sound_enabled);
466 sound_manager->enable_music(g_config->music_enabled);
472 if(sound_manager != NULL) {
473 delete sound_manager;
474 sound_manager = NULL;
479 Main::wait_for_event(float min_delay, float max_delay)
481 assert(min_delay <= max_delay);
483 Uint32 min = (Uint32) (min_delay * 1000);
484 Uint32 max = (Uint32) (max_delay * 1000);
486 Uint32 ticks = SDL_GetTicks();
487 while(SDL_GetTicks() - ticks < min) {
489 sound_manager->update();
494 while (SDL_PollEvent(&event))
498 bool running = false;
499 ticks = SDL_GetTicks();
501 while(SDL_PollEvent(&event)) {
504 g_screen_manager->quit();
507 case SDL_JOYBUTTONDOWN:
508 case SDL_MOUSEBUTTONDOWN:
512 if(SDL_GetTicks() - ticks >= (max - min))
514 sound_manager->update();
520 static Uint32 last_timelog_ticks = 0;
521 static const char* last_timelog_component = 0;
523 static inline void timelog(const char* component)
525 Uint32 current_ticks = SDL_GetTicks();
527 if(last_timelog_component != 0) {
528 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
531 last_timelog_ticks = current_ticks;
532 last_timelog_component = component;
535 static inline void timelog(const char* )
541 Main::main(int argc, char** argv)
547 if(pre_parse_commandline(argc, argv))
550 Console::instance = new Console();
551 init_physfs(argv[0]);
554 timelog("controller");
555 g_main_controller = new JoystickKeyboardController();
561 AddonManager::get_instance().load_addons();
563 timelog("tinygettext");
566 timelog("commandline");
567 if(parse_commandline(argc, argv))
574 DrawingContext context;
575 context_pointer = &context;
578 Console::instance->init_graphics();
580 timelog("scripting");
581 Scripting::init_squirrel(g_config->enable_script_debugger);
583 timelog("resources");
584 Resources::load_shared();
588 g_screen_manager = new ScreenManager();
589 if(g_config->start_level != "") {
590 // we have a normal path specified at commandline, not a physfs path.
591 // So we simply mount that path here...
592 std::string dir = FileSystem::dirname(g_config->start_level);
593 log_debug << "Adding dir: " << dir << std::endl;
594 PHYSFS_addToSearchPath(dir.c_str(), true);
596 if(g_config->start_level.size() > 4 &&
597 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
599 g_screen_manager->push_screen(new WorldMapNS::WorldMap(
600 FileSystem::basename(g_config->start_level)));
602 init_rand();//If level uses random eg. for
603 // rain particles before we do this:
604 std::auto_ptr<GameSession> session (
605 new GameSession(FileSystem::basename(g_config->start_level)));
607 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
608 init_rand();//initialise generator with seed from session
610 if(g_config->start_demo != "")
611 session->play_demo(g_config->start_demo);
613 if(g_config->record_demo != "")
614 session->record_demo(g_config->record_demo);
615 g_screen_manager->push_screen(session.release());
619 g_screen_manager->push_screen(new TitleScreen());
622 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
623 g_screen_manager->run(context);
624 } catch(std::exception& e) {
625 log_fatal << "Unexpected exception: " << e.what() << std::endl;
628 log_fatal << "Unexpected exception" << std::endl;
632 delete g_screen_manager;
633 g_screen_manager = NULL;
635 Resources::unload_shared();
642 delete g_main_controller;
643 g_main_controller = NULL;
644 delete Console::instance;
645 Console::instance = NULL;
646 Scripting::exit_squirrel();
647 delete texture_manager;
648 texture_manager = NULL;