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