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/>.
20 #include <SDL_image.h>
24 #include <tinygettext/log.hpp>
25 #include <boost/format.hpp>
28 #include <findlocale.h>
31 #include "video/renderer.hpp"
32 #include "video/lightmap.hpp"
33 #include "supertux/main.hpp"
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/input_manager.hpp"
38 #include "math/random_generator.hpp"
39 #include "physfs/ifile_stream.hpp"
40 #include "physfs/physfs_file_system.hpp"
41 #include "physfs/physfs_sdl.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/gameconfig.hpp"
44 #include "supertux/globals.hpp"
45 #include "supertux/player_status.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/screen_fade.hpp"
48 #include "supertux/screen_manager.hpp"
49 #include "supertux/title_screen.hpp"
50 #include "util/file_system.hpp"
51 #include "util/gettext.hpp"
52 #include "video/drawing_context.hpp"
53 #include "worldmap/worldmap.hpp"
55 namespace { DrawingContext *context_pointer; }
58 # define WRITEDIR_NAME PACKAGE_NAME
60 # define WRITEDIR_NAME "." PACKAGE_NAME
66 g_config = new Config();
69 } catch(std::exception& e) {
70 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
75 Main::init_tinygettext()
77 dictionary_manager = new tinygettext::DictionaryManager();
78 tinygettext::Log::set_log_info_callback(0);
79 dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
81 dictionary_manager->add_directory("locale");
82 dictionary_manager->set_charset("UTF-8");
84 // Config setting "locale" overrides language detection
85 if (g_config->locale != "")
87 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
90 FL_FindLocale(&locale);
91 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
92 FL_FreeLocale(&locale);
93 dictionary_manager->set_language(language);
98 Main::init_physfs(const char* argv0)
100 if(!PHYSFS_init(argv0)) {
101 std::stringstream msg;
102 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
103 throw std::runtime_error(msg.str());
106 // allow symbolic links
107 PHYSFS_permitSymbolicLinks(1);
109 // Initialize physfs (this is a slightly modified version of
110 // PHYSFS_setSaneConfig)
111 const char *env_writedir;
112 std::string writedir;
114 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
115 writedir = env_writedir;
116 if(!PHYSFS_setWriteDir(writedir.c_str())) {
117 std::ostringstream msg;
118 msg << "Failed to use configuration directory '"
119 << writedir << "': " << PHYSFS_getLastError();
120 throw std::runtime_error(msg.str());
124 std::string userdir = PHYSFS_getUserDir();
126 // Set configuration directory
127 writedir = userdir + WRITEDIR_NAME;
128 if(!PHYSFS_setWriteDir(writedir.c_str())) {
129 // try to create the directory
130 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
131 std::ostringstream msg;
132 msg << "Failed creating configuration directory '"
133 << writedir << "': " << PHYSFS_getLastError();
134 throw std::runtime_error(msg.str());
137 if(!PHYSFS_setWriteDir(writedir.c_str())) {
138 std::ostringstream msg;
139 msg << "Failed to use configuration directory '"
140 << writedir << "': " << PHYSFS_getLastError();
141 throw std::runtime_error(msg.str());
145 PHYSFS_addToSearchPath(writedir.c_str(), 0);
147 // when started from source dir...
148 char* base_path = SDL_GetBasePath();
149 std::string dir = base_path;
152 if (dir[dir.length() - 1] != '/')
155 std::string testfname = dir;
156 testfname += "/credits.txt";
157 bool sourcedir = false;
158 FILE* f = fopen(testfname.c_str(), "r");
161 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
162 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
169 std::string datadir = PHYSFS_getBaseDir();
170 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
171 datadir += "/" INSTALL_SUBDIR_SHARE;
172 #ifdef ENABLE_BINRELOC
176 dir = br_find_data_dir(datadir.c_str());
181 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
182 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
187 char** searchpath = PHYSFS_getSearchPath();
188 for(char** i = searchpath; *i != NULL; i++)
189 log_info << "[" << *i << "] is in the search path" << std::endl;
190 PHYSFS_freeList(searchpath);
194 Main::print_usage(const char* argv0)
196 std::string default_user_data_dir =
197 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
199 std::cerr << boost::format(_(
201 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
203 " -f, --fullscreen Run in fullscreen mode\n"
204 " -w, --window Run in window mode\n"
205 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
206 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
207 " -d, --default Reset video settings to default values\n"
208 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
209 " --disable-sfx Disable sound effects\n"
210 " --disable-music Disable music\n"
211 " -h, --help Show this help message and quit\n"
212 " -v, --version Show SuperTux version and quit\n"
213 " --console Enable ingame scripting console\n"
214 " --noconsole Disable ingame scripting console\n"
215 " --show-fps Display framerate in levels\n"
216 " --no-show-fps Do not display framerate in levels\n"
217 " --record-demo FILE LEVEL Record a demo to FILE\n"
218 " --play-demo FILE LEVEL Play a recorded demo\n"
219 " -s, --debug-scripts Enable script debugger.\n"
220 " --print-datadir Print supertux's primary data directory.\n"
222 "Environment variables:\n"
223 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
227 % argv0 % default_user_data_dir
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]);
248 if(arg == "--print-datadir") {
250 * Print the datadir searchpath to stdout, one path per
251 * line. Then exit. Intended for use by the supertux-editor.
255 sp = PHYSFS_getSearchPath();
257 for (sp_index = 0; sp[sp_index]; sp_index++)
258 std::cout << sp[sp_index] << std::endl;
268 * Options that should be evaluated after config is read go here
271 Main::parse_commandline(int argc, char** argv)
273 for(int i = 1; i < argc; ++i) {
274 std::string arg = argv[i];
276 if(arg == "--fullscreen" || arg == "-f") {
277 g_config->use_fullscreen = true;
278 } else if(arg == "--default" || arg == "-d") {
279 g_config->use_fullscreen = false;
281 g_config->window_size = Size(800, 600);
282 g_config->fullscreen_size = Size(800, 600);
283 g_config->fullscreen_refresh_rate = 0;
284 g_config->aspect_size = Size(0, 0); // auto detect
286 } else if(arg == "--window" || arg == "-w") {
287 g_config->use_fullscreen = false;
288 } else if(arg == "--geometry" || arg == "-g") {
292 print_usage(argv[0]);
293 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
298 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
300 print_usage(argv[0]);
301 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
305 g_config->window_size = Size(width, height);
306 g_config->fullscreen_size = Size(width, height);
307 g_config->fullscreen_refresh_rate = 0;
310 } else if(arg == "--aspect" || arg == "-a") {
314 print_usage(argv[0]);
315 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
319 int aspect_width = 0;
320 int aspect_height = 0;
321 if (strcmp(argv[i], "auto") == 0)
326 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
328 print_usage(argv[0]);
329 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
333 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
335 // use aspect ratio to calculate logical resolution
336 if (aspect_ratio > 1) {
337 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
340 g_config->aspect_size = Size(600,
341 static_cast<int>(600 * 1/aspect_ratio + 0.5));
345 } else if(arg == "--renderer") {
349 print_usage(argv[0]);
350 throw std::runtime_error("Need to specify a renderer for renderer argument");
354 g_config->video = VideoSystem::get_video_system(argv[i]);
356 } else if(arg == "--show-fps") {
357 g_config->show_fps = true;
358 } else if(arg == "--no-show-fps") {
359 g_config->show_fps = false;
360 } else if(arg == "--console") {
361 g_config->console_enabled = true;
362 } else if(arg == "--noconsole") {
363 g_config->console_enabled = false;
364 } else if(arg == "--disable-sfx") {
365 g_config->sound_enabled = false;
366 } else if(arg == "--disable-music") {
367 g_config->music_enabled = false;
368 } else if(arg == "--play-demo") {
370 print_usage(argv[0]);
371 throw std::runtime_error("Need to specify a demo filename");
373 g_config->start_demo = argv[++i];
374 } else if(arg == "--record-demo") {
376 print_usage(argv[0]);
377 throw std::runtime_error("Need to specify a demo filename");
379 g_config->record_demo = argv[++i];
380 } else if(arg == "--debug-scripts" || arg == "-s") {
381 g_config->enable_script_debugger = true;
382 } else if(arg[0] != '-') {
383 g_config->start_level = arg;
385 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
395 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
396 std::stringstream msg;
397 msg << "Couldn't initialize SDL: " << SDL_GetError();
398 throw std::runtime_error(msg.str());
407 g_config->random_seed = gameRandom.srand(g_config->random_seed);
409 graphicsRandom.srand(0);
411 //const char *how = config->random_seed? ", user fixed.": ", from time().";
412 //log_info << "Using random seed " << config->random_seed << how << std::endl;
418 SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
420 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
421 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
424 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
428 SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
429 SDL_FreeSurface(icon);
433 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
434 << " Window: " << g_config->window_size
435 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
436 << " Area: " << g_config->aspect_size << std::endl;
442 sound_manager = new SoundManager();
444 sound_manager->enable_sound(g_config->sound_enabled);
445 sound_manager->enable_music(g_config->music_enabled);
451 if(sound_manager != NULL) {
452 delete sound_manager;
453 sound_manager = NULL;
457 static Uint32 last_timelog_ticks = 0;
458 static const char* last_timelog_component = 0;
460 static inline void timelog(const char* component)
462 Uint32 current_ticks = SDL_GetTicks();
464 if(last_timelog_component != 0) {
465 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
468 last_timelog_ticks = current_ticks;
469 last_timelog_component = component;
473 Main::run(int argc, char** argv)
478 /* Do this before pre_parse_commandline, because --help now shows the
479 * default user data dir. */
480 init_physfs(argv[0]);
482 if(pre_parse_commandline(argc, argv))
486 Console::instance = new Console();
488 timelog("controller");
489 g_input_manager = new InputManager();
494 timelog("commandline");
495 if(parse_commandline(argc, argv))
499 std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
500 std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
501 DrawingContext context(*renderer, *lightmap);
502 context_pointer = &context;
508 timelog("tinygettext");
511 Console::instance->init_graphics();
513 timelog("scripting");
514 scripting::init_squirrel(g_config->enable_script_debugger);
516 timelog("resources");
517 Resources::load_shared();
520 AddonManager::get_instance().load_addons();
524 const std::unique_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
526 g_screen_manager = new ScreenManager();
530 if(g_config->start_level != "") {
531 // we have a normal path specified at commandline, not a physfs path.
532 // So we simply mount that path here...
533 std::string dir = FileSystem::dirname(g_config->start_level);
534 std::string fileProtocol = "file://";
535 std::string::size_type position = dir.find(fileProtocol);
536 if(position != std::string::npos) {
537 dir = dir.replace(position, fileProtocol.length(), "");
539 log_debug << "Adding dir: " << dir << std::endl;
540 PHYSFS_addToSearchPath(dir.c_str(), true);
542 if(g_config->start_level.size() > 4 &&
543 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
544 g_screen_manager->push_screen(std::unique_ptr<Screen>(
545 new worldmap::WorldMap(
546 FileSystem::basename(g_config->start_level), default_playerstatus.get())));
548 std::unique_ptr<GameSession> session (
549 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
551 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
552 init_rand();//initialise generator with seed from session
554 if(g_config->start_demo != "")
555 session->play_demo(g_config->start_demo);
557 if(g_config->record_demo != "")
558 session->record_demo(g_config->record_demo);
559 g_screen_manager->push_screen(std::move(session));
562 g_screen_manager->push_screen(std::unique_ptr<Screen>(new TitleScreen(default_playerstatus.get())));
565 g_screen_manager->run(context);
566 } catch(std::exception& e) {
567 log_fatal << "Unexpected exception: " << e.what() << std::endl;
570 log_fatal << "Unexpected exception" << std::endl;
574 delete g_screen_manager;
575 g_screen_manager = NULL;
577 Resources::unload_shared();
584 delete g_input_manager;
585 g_input_manager = NULL;
586 delete Console::instance;
587 Console::instance = NULL;
588 scripting::exit_squirrel();
589 delete texture_manager;
590 texture_manager = NULL;