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>
27 #include <boost/format.hpp>
30 #include <findlocale.h>
33 #include "addon/addon_manager.hpp"
34 #include "audio/sound_manager.hpp"
35 #include "control/input_manager.hpp"
36 #include "math/random_generator.hpp"
37 #include "physfs/ifile_stream.hpp"
38 #include "physfs/physfs_file_system.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "scripting/squirrel_util.hpp"
41 #include "sprite/sprite_manager.hpp"
42 #include "supertux/command_line_arguments.hpp"
43 #include "supertux/game_manager.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/resources.hpp"
48 #include "supertux/screen_fade.hpp"
49 #include "supertux/screen_manager.hpp"
50 #include "supertux/title_screen.hpp"
51 #include "util/file_system.hpp"
52 #include "util/gettext.hpp"
53 #include "video/drawing_context.hpp"
54 #include "video/lightmap.hpp"
55 #include "video/renderer.hpp"
56 #include "worldmap/worldmap.hpp"
61 g_config.reset(new Config);
64 } catch(const std::exception& e) {
65 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
68 // init random number stuff
69 g_config->random_seed = gameRandom.srand(g_config->random_seed);
70 graphicsRandom.srand(0);
71 //const char *how = config->random_seed? ", user fixed.": ", from time().";
72 //log_info << "Using random seed " << config->random_seed << how << std::endl;
76 Main::init_tinygettext()
78 g_dictionary_manager.reset(new tinygettext::DictionaryManager);
79 tinygettext::Log::set_log_info_callback(0);
80 g_dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
82 g_dictionary_manager->add_directory("locale");
83 g_dictionary_manager->set_charset("UTF-8");
85 // Config setting "locale" overrides language detection
86 if (g_config->locale != "")
88 g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
93 FL_FindLocale(&locale);
94 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
95 FL_FreeLocale(&locale);
96 g_dictionary_manager->set_language(language);
100 class PhysfsSubsystem
103 PhysfsSubsystem(const char* argv0)
105 if(!PHYSFS_init(argv0)) {
106 std::stringstream msg;
107 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
108 throw std::runtime_error(msg.str());
111 // allow symbolic links
112 PHYSFS_permitSymbolicLinks(1);
114 // Initialize physfs (this is a slightly modified version of
115 // PHYSFS_setSaneConfig)
116 const char *env_writedir;
117 std::string writedir;
119 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
120 writedir = env_writedir;
121 if(!PHYSFS_setWriteDir(writedir.c_str())) {
122 std::ostringstream msg;
123 msg << "Failed to use configuration directory '"
124 << writedir << "': " << PHYSFS_getLastError();
125 throw std::runtime_error(msg.str());
129 std::string userdir = PHYSFS_getUserDir();
131 // Set configuration directory
132 writedir = userdir + WRITEDIR_NAME;
133 if(!PHYSFS_setWriteDir(writedir.c_str())) {
134 // try to create the directory
135 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
136 std::ostringstream msg;
137 msg << "Failed creating configuration directory '"
138 << writedir << "': " << PHYSFS_getLastError();
139 throw std::runtime_error(msg.str());
142 if(!PHYSFS_setWriteDir(writedir.c_str())) {
143 std::ostringstream msg;
144 msg << "Failed to use configuration directory '"
145 << writedir << "': " << PHYSFS_getLastError();
146 throw std::runtime_error(msg.str());
150 PHYSFS_addToSearchPath(writedir.c_str(), 0);
152 // when started from source dir...
153 char* base_path = SDL_GetBasePath();
154 std::string dir = base_path;
157 if (dir[dir.length() - 1] != '/')
160 std::string testfname = dir;
161 testfname += "/credits.txt";
162 bool sourcedir = false;
163 FILE* 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;
174 std::string datadir = PHYSFS_getBaseDir();
175 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
176 datadir += "/" INSTALL_SUBDIR_SHARE;
177 #ifdef ENABLE_BINRELOC
181 dir = br_find_data_dir(datadir.c_str());
186 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
187 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
192 char** searchpath = PHYSFS_getSearchPath();
193 for(char** i = searchpath; *i != NULL; i++)
194 log_info << "[" << *i << "] is in the search path" << std::endl;
195 PHYSFS_freeList(searchpath);
209 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
211 std::stringstream msg;
212 msg << "Couldn't initialize SDL: " << SDL_GetError();
213 throw std::runtime_error(msg.str());
228 SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
230 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
231 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
234 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
238 SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
239 SDL_FreeSurface(icon);
243 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
244 << " Window: " << g_config->window_size
245 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
246 << " Area: " << g_config->aspect_size << std::endl;
249 static Uint32 last_timelog_ticks = 0;
250 static const char* last_timelog_component = 0;
252 static inline void timelog(const char* component)
254 Uint32 current_ticks = SDL_GetTicks();
256 if(last_timelog_component != 0) {
257 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
260 last_timelog_ticks = current_ticks;
261 last_timelog_component = component;
267 SDLSubsystem sdl_subsystem;
268 ConsoleBuffer console_buffer;
270 timelog("controller");
271 InputManager input_manager;
273 timelog("commandline");
276 std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
277 DrawingContext context(video_system->get_renderer(),
278 video_system->get_lightmap());
282 SoundManager sound_manager;
283 sound_manager.enable_sound(g_config->sound_enabled);
284 sound_manager.enable_music(g_config->music_enabled);
286 Console console(console_buffer);
288 timelog("scripting");
289 scripting::init_squirrel(g_config->enable_script_debugger);
291 timelog("resources");
292 TileManager tile_manager;
293 SpriteManager sprite_manager;
297 AddonManager::get_instance().load_addons();
301 const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
303 GameManager game_manager;
304 ScreenManager screen_manager;
306 if(g_config->start_level != "") {
307 // we have a normal path specified at commandline, not a physfs path.
308 // So we simply mount that path here...
309 std::string dir = FileSystem::dirname(g_config->start_level);
310 std::string fileProtocol = "file://";
311 std::string::size_type position = dir.find(fileProtocol);
312 if(position != std::string::npos) {
313 dir = dir.replace(position, fileProtocol.length(), "");
315 log_debug << "Adding dir: " << dir << std::endl;
316 PHYSFS_addToSearchPath(dir.c_str(), true);
318 if(g_config->start_level.size() > 4 &&
319 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
321 screen_manager.push_screen(std::unique_ptr<Screen>(
322 new worldmap::WorldMap(
323 FileSystem::basename(g_config->start_level), *default_savegame)));
325 std::unique_ptr<GameSession> session (
326 new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
328 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
329 init_rand();//initialise generator with seed from session
331 if(g_config->start_demo != "")
332 session->play_demo(g_config->start_demo);
334 if(g_config->record_demo != "")
335 session->record_demo(g_config->record_demo);
336 screen_manager.push_screen(std::move(session));
339 screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
342 screen_manager.run(context);
346 Main::run(int argc, char** argv)
352 CommandLineArguments args;
354 // Do this before pre_parse_commandline, because --help now shows the
355 // default user data dir.
356 PhysfsSubsystem physfs_subsystem(argv[0]);
360 args.parse_args(argc, argv);
361 g_log_level = args.get_log_level();
363 catch(const std::exception& err)
368 args.merge_into(*g_config);
371 catch(const std::exception& err_)
373 log_fatal << "failed to init config or tinygettext: " << err_.what() << std::endl;
376 std::cout << "Error: " << err.what() << std::endl;
382 args.merge_into(*g_config);
384 timelog("tinygettext");
387 switch (args.get_action())
389 case CommandLineArguments::PRINT_VERSION:
390 args.print_version();
393 case CommandLineArguments::PRINT_HELP:
394 args.print_help(argv[0]);
397 case CommandLineArguments::PRINT_DATADIR:
398 args.print_datadir();
406 catch(const std::exception& e)
408 log_fatal << "Unexpected exception: " << e.what() << std::endl;
413 log_fatal << "Unexpected exception" << std::endl;
421 scripting::exit_squirrel();
423 g_dictionary_manager.reset();