Cleaned up Physfs/filesystem initialisation
[supertux.git] / src / supertux / main.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
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.
8 //
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.
13 //
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/>.
16
17 #include "supertux/main.hpp"
18
19 #include <config.h>
20 #include <version.h>
21
22 #include <SDL_image.h>
23 #include <physfs.h>
24 #include <iostream>
25 #include <tinygettext/log.hpp>
26 #include <boost/format.hpp>
27 #include <stdio.h>
28 extern "C" {
29 #include <findlocale.h>
30 }
31
32 #include "addon/addon_manager.hpp"
33 #include "audio/sound_manager.hpp"
34 #include "control/input_manager.hpp"
35 #include "math/random_generator.hpp"
36 #include "physfs/ifile_stream.hpp"
37 #include "physfs/physfs_file_system.hpp"
38 #include "physfs/physfs_sdl.hpp"
39 #include "scripting/squirrel_util.hpp"
40 #include "scripting/scripting.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"
57
58 class ConfigSubsystem
59 {
60 public:
61   ConfigSubsystem()
62   {
63     g_config.reset(new Config);
64     try {
65       g_config->load();
66     }
67     catch(const std::exception& e)
68     {
69       log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
70     }
71
72     // init random number stuff
73     g_config->random_seed = gameRandom.srand(g_config->random_seed);
74     graphicsRandom.srand(0);
75     //const char *how = config->random_seed? ", user fixed.": ", from time().";
76     //log_info << "Using random seed " << config->random_seed << how << std::endl;
77   }
78
79   ~ConfigSubsystem()
80   {
81     if (g_config)
82     {
83       g_config->save();
84     }
85     g_config.reset();
86   }
87 };
88
89 void
90 Main::init_tinygettext()
91 {
92   g_dictionary_manager.reset(new tinygettext::DictionaryManager);
93   tinygettext::Log::set_log_info_callback(0);
94   g_dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
95
96   g_dictionary_manager->add_directory("locale");
97   g_dictionary_manager->set_charset("UTF-8");
98
99   // Config setting "locale" overrides language detection
100   if (g_config->locale != "")
101   {
102     g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
103   }
104   else
105   {
106     FL_Locale *locale;
107     FL_FindLocale(&locale);
108     tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
109     FL_FreeLocale(&locale);
110     g_dictionary_manager->set_language(language);
111   }
112 }
113
114 class PhysfsSubsystem
115 {
116 public:
117   PhysfsSubsystem(const char* argv0)
118   {
119     if (!PHYSFS_init(argv0))
120     {
121       std::stringstream msg;
122       msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
123       throw std::runtime_error(msg.str());
124     }
125     else
126     {
127       // allow symbolic links
128       PHYSFS_permitSymbolicLinks(1);
129
130       find_userdir();
131       find_datadir();
132     }
133   }
134
135   void find_datadir()
136   {
137     // check if we run from source dir
138     char* basepath_c = SDL_GetBasePath();
139     std::string basepath = basepath_c;
140     SDL_free(basepath_c);
141
142     std::string datadir = FileSystem::join(basepath, "data");
143     std::string testfname = FileSystem::join(datadir, "credits.txt");
144     if (!FileSystem::exists(testfname))
145     {
146       // if the game is not run from the source directory, try to find
147       // the global install location
148       datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
149       datadir = FileSystem::join(datadir, INSTALL_SUBDIR_SHARE);
150     }
151
152     if (!PHYSFS_addToSearchPath(datadir.c_str(), 1))
153     {
154       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
155     }
156   }
157
158   void find_userdir()
159   {
160 #ifdef _WIN32
161 # define WRITEDIR_NAME PACKAGE_NAME
162 #else
163 # define WRITEDIR_NAME "." PACKAGE_NAME
164 #endif
165
166     std::string writedir;
167
168     const char* env_writedir = getenv("SUPERTUX2_USER_DIR");
169     if (env_writedir)
170     {
171       writedir = env_writedir;
172     }
173     else
174     {
175       std::string userdir = PHYSFS_getUserDir();
176       writedir = FileSystem::join(userdir, WRITEDIR_NAME);
177     }
178
179     if (!FileSystem::is_directory(writedir))
180     {
181       FileSystem::mkdir(writedir);
182       log_info << "Created SuperTux userdir: " << writedir << std::endl;
183     }
184
185     if (!PHYSFS_setWriteDir(writedir.c_str()))
186     {
187       std::ostringstream msg;
188       msg << "Failed to use configuration directory '"
189           <<  writedir << "': " << PHYSFS_getLastError();
190       throw std::runtime_error(msg.str());
191     }
192
193     PHYSFS_addToSearchPath(writedir.c_str(), 0);
194   }
195
196   void print_search_path()
197   {
198     char** searchpath = PHYSFS_getSearchPath();
199     for(char** i = searchpath; *i != NULL; ++i)
200     {
201       log_info << "[" << *i << "] is in the search path" << std::endl;
202     }
203     PHYSFS_freeList(searchpath);
204   }
205
206   ~PhysfsSubsystem()
207   {
208     PHYSFS_deinit();
209   }
210 };
211
212 class SDLSubsystem
213 {
214 public:
215   SDLSubsystem()
216   {
217     if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
218     {
219       std::stringstream msg;
220       msg << "Couldn't initialize SDL: " << SDL_GetError();
221       throw std::runtime_error(msg.str());
222     }
223     // just to be sure
224     atexit(SDL_Quit);
225   }
226
227   ~SDLSubsystem()
228   {
229     SDL_Quit();
230   }
231 };
232
233 void
234 Main::init_video()
235 {
236   SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
237
238   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
239   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
240   if (!icon)
241   {
242     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
243   }
244   else
245   {
246     SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
247     SDL_FreeSurface(icon);
248   }
249   SDL_ShowCursor(0);
250
251   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
252            << " Window: "     << g_config->window_size
253            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
254            << " Area: "       << g_config->aspect_size << std::endl;
255 }
256
257 static Uint32 last_timelog_ticks = 0;
258 static const char* last_timelog_component = 0;
259
260 static inline void timelog(const char* component)
261 {
262   Uint32 current_ticks = SDL_GetTicks();
263
264   if(last_timelog_component != 0) {
265     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
266   }
267
268   last_timelog_ticks = current_ticks;
269   last_timelog_component = component;
270 }
271
272 void
273 Main::launch_game()
274 {
275   SDLSubsystem sdl_subsystem;
276   ConsoleBuffer console_buffer;
277
278   timelog("controller");
279   InputManager input_manager(g_config->keyboard_config, g_config->joystick_config);
280
281   timelog("commandline");
282
283   timelog("video");
284   std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
285   DrawingContext context(video_system->get_renderer(),
286                          video_system->get_lightmap());
287   init_video();
288
289   timelog("audio");
290   SoundManager sound_manager;
291   sound_manager.enable_sound(g_config->sound_enabled);
292   sound_manager.enable_music(g_config->music_enabled);
293
294   Console console(console_buffer);
295
296   timelog("scripting");
297   scripting::Scripting scripting(g_config->enable_script_debugger);
298
299   timelog("resources");
300   TileManager tile_manager;
301   SpriteManager sprite_manager;
302   Resources resources;
303
304   timelog("addons");
305   AddonManager addon_manager(g_config->disabled_addon_filenames);
306   addon_manager.load_addons();
307
308   timelog(0);
309
310   const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
311
312   GameManager game_manager;
313   ScreenManager screen_manager;
314
315   if(g_config->start_level != "") {
316     // we have a normal path specified at commandline, not a physfs path.
317     // So we simply mount that path here...
318     std::string dir = FileSystem::dirname(g_config->start_level);
319     std::string fileProtocol = "file://";
320     std::string::size_type position = dir.find(fileProtocol);
321     if(position != std::string::npos) {
322       dir = dir.replace(position, fileProtocol.length(), "");
323     }
324     log_debug << "Adding dir: " << dir << std::endl;
325     PHYSFS_addToSearchPath(dir.c_str(), true);
326
327     if(g_config->start_level.size() > 4 &&
328        g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
329     {
330       screen_manager.push_screen(std::unique_ptr<Screen>(
331                                               new worldmap::WorldMap(
332                                                 FileSystem::basename(g_config->start_level), *default_savegame)));
333     } else {
334       std::unique_ptr<GameSession> session (
335         new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
336
337       g_config->random_seed = session->get_demo_random_seed(g_config->start_demo);
338       g_config->random_seed = gameRandom.srand(g_config->random_seed);
339       graphicsRandom.srand(0);
340
341       if(g_config->start_demo != "")
342         session->play_demo(g_config->start_demo);
343
344       if(g_config->record_demo != "")
345         session->record_demo(g_config->record_demo);
346       screen_manager.push_screen(std::move(session));
347     }
348   } else {
349     screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
350   }
351
352   screen_manager.run(context);
353 }
354
355 int
356 Main::run(int argc, char** argv)
357 {
358   int result = 0;
359
360   try
361   {
362     CommandLineArguments args;
363
364     try
365     {
366       args.parse_args(argc, argv);
367       g_log_level = args.get_log_level();
368     }
369     catch(const std::exception& err)
370     {
371       std::cout << "Error: " << err.what() << std::endl;
372       return EXIT_FAILURE;
373     }
374
375     PhysfsSubsystem physfs_subsystem(argv[0]);
376     physfs_subsystem.print_search_path();
377
378     timelog("config");
379     ConfigSubsystem config_subsystem;
380     args.merge_into(*g_config);
381
382     timelog("tinygettext");
383     init_tinygettext();
384
385     switch (args.get_action())
386     {
387       case CommandLineArguments::PRINT_VERSION:
388         args.print_version();
389         return 0;
390
391       case CommandLineArguments::PRINT_HELP:
392         args.print_help(argv[0]);
393         return 0;
394
395       case CommandLineArguments::PRINT_DATADIR:
396         args.print_datadir();
397         return 0;
398
399       default:
400         launch_game();
401         break;
402     }
403   }
404   catch(const std::exception& e)
405   {
406     log_fatal << "Unexpected exception: " << e.what() << std::endl;
407     result = 1;
408   }
409   catch(...)
410   {
411     log_fatal << "Unexpected exception" << std::endl;
412     result = 1;
413   }
414
415   g_dictionary_manager.reset();
416
417   return result;
418 }
419
420 /* EOF */