Removed binreloc support, SDL2 provides that functionality now with SDL_GetBasePath()
[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 <binreloc.h>
26 #include <tinygettext/log.hpp>
27 #include <boost/format.hpp>
28 #include <stdio.h>
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 public:
118   PhysfsSubsystem(const char* argv0)
119   {
120     if(!PHYSFS_init(argv0)) {
121       std::stringstream msg;
122       msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
123       throw std::runtime_error(msg.str());
124     }
125
126     // allow symbolic links
127     PHYSFS_permitSymbolicLinks(1);
128
129     // Initialize physfs (this is a slightly modified version of
130     // PHYSFS_setSaneConfig)
131     const char *env_writedir;
132     std::string writedir;
133
134     if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
135       writedir = env_writedir;
136       if(!PHYSFS_setWriteDir(writedir.c_str())) {
137         std::ostringstream msg;
138         msg << "Failed to use configuration directory '"
139             <<  writedir << "': " << PHYSFS_getLastError();
140         throw std::runtime_error(msg.str());
141       }
142
143     } else {
144       std::string userdir = PHYSFS_getUserDir();
145
146       // Set configuration directory
147       writedir = userdir + WRITEDIR_NAME;
148       if(!PHYSFS_setWriteDir(writedir.c_str())) {
149         // try to create the directory
150         if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
151           std::ostringstream msg;
152           msg << "Failed creating configuration directory '"
153               << writedir << "': " << PHYSFS_getLastError();
154           throw std::runtime_error(msg.str());
155         }
156
157         if(!PHYSFS_setWriteDir(writedir.c_str())) {
158           std::ostringstream msg;
159           msg << "Failed to use configuration directory '"
160               <<  writedir << "': " << PHYSFS_getLastError();
161           throw std::runtime_error(msg.str());
162         }
163       }
164     }
165     PHYSFS_addToSearchPath(writedir.c_str(), 0);
166
167     // when started from source dir...
168     char* base_path = SDL_GetBasePath();
169     std::string dir = base_path;
170     SDL_free(base_path);
171
172     if (dir[dir.length() - 1] != '/')
173       dir += "/";
174     dir += "data";
175     std::string testfname = dir;
176     testfname += "/credits.txt";
177     bool sourcedir = false;
178     FILE* f = fopen(testfname.c_str(), "r");
179     if(f) {
180       fclose(f);
181       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
182         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
183       } else {
184         sourcedir = true;
185       }
186     }
187
188     if(!sourcedir) {
189       std::string datadir = PHYSFS_getBaseDir();
190       datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
191       datadir += "/" INSTALL_SUBDIR_SHARE;
192       if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
193         log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
194       }
195     }
196
197     //show search Path
198     char** searchpath = PHYSFS_getSearchPath();
199     for(char** i = searchpath; *i != NULL; i++)
200       log_info << "[" << *i << "] is in the search path" << std::endl;
201     PHYSFS_freeList(searchpath);
202   }
203
204   ~PhysfsSubsystem()
205   {
206     PHYSFS_deinit();
207   }
208 };
209
210 class SDLSubsystem
211 {
212 public:
213   SDLSubsystem()
214   {
215     if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
216     {
217       std::stringstream msg;
218       msg << "Couldn't initialize SDL: " << SDL_GetError();
219       throw std::runtime_error(msg.str());
220     }
221     // just to be sure
222     atexit(SDL_Quit);
223   }
224
225   ~SDLSubsystem()
226   {
227     SDL_Quit();
228   }
229 };
230
231 void
232 Main::init_video()
233 {
234   SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
235
236   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
237   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
238   if (!icon)
239   {
240     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
241   }
242   else
243   {
244     SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
245     SDL_FreeSurface(icon);
246   }
247   SDL_ShowCursor(0);
248
249   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
250            << " Window: "     << g_config->window_size
251            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
252            << " Area: "       << g_config->aspect_size << std::endl;
253 }
254
255 static Uint32 last_timelog_ticks = 0;
256 static const char* last_timelog_component = 0;
257
258 static inline void timelog(const char* component)
259 {
260   Uint32 current_ticks = SDL_GetTicks();
261
262   if(last_timelog_component != 0) {
263     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
264   }
265
266   last_timelog_ticks = current_ticks;
267   last_timelog_component = component;
268 }
269
270 void
271 Main::launch_game()
272 {
273   SDLSubsystem sdl_subsystem;
274   ConsoleBuffer console_buffer;
275
276   timelog("controller");
277   InputManager input_manager(g_config->keyboard_config, g_config->joystick_config);
278
279   timelog("commandline");
280
281   timelog("video");
282   std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
283   DrawingContext context(video_system->get_renderer(),
284                          video_system->get_lightmap());
285   init_video();
286
287   timelog("audio");
288   SoundManager sound_manager;
289   sound_manager.enable_sound(g_config->sound_enabled);
290   sound_manager.enable_music(g_config->music_enabled);
291
292   Console console(console_buffer);
293
294   timelog("scripting");
295   scripting::Scripting scripting(g_config->enable_script_debugger);
296
297   timelog("resources");
298   TileManager tile_manager;
299   SpriteManager sprite_manager;
300   Resources resources;
301
302   timelog("addons");
303   AddonManager addon_manager(g_config->disabled_addon_filenames);
304   addon_manager.load_addons();
305
306   timelog(0);
307
308   const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
309
310   GameManager game_manager;
311   ScreenManager screen_manager;
312
313   if(g_config->start_level != "") {
314     // we have a normal path specified at commandline, not a physfs path.
315     // So we simply mount that path here...
316     std::string dir = FileSystem::dirname(g_config->start_level);
317     std::string fileProtocol = "file://";
318     std::string::size_type position = dir.find(fileProtocol);
319     if(position != std::string::npos) {
320       dir = dir.replace(position, fileProtocol.length(), "");
321     }
322     log_debug << "Adding dir: " << dir << std::endl;
323     PHYSFS_addToSearchPath(dir.c_str(), true);
324
325     if(g_config->start_level.size() > 4 &&
326        g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
327     {
328       screen_manager.push_screen(std::unique_ptr<Screen>(
329                                               new worldmap::WorldMap(
330                                                 FileSystem::basename(g_config->start_level), *default_savegame)));
331     } else {
332       std::unique_ptr<GameSession> session (
333         new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
334
335       g_config->random_seed = session->get_demo_random_seed(g_config->start_demo);
336       g_config->random_seed = gameRandom.srand(g_config->random_seed);
337       graphicsRandom.srand(0);
338
339       if(g_config->start_demo != "")
340         session->play_demo(g_config->start_demo);
341
342       if(g_config->record_demo != "")
343         session->record_demo(g_config->record_demo);
344       screen_manager.push_screen(std::move(session));
345     }
346   } else {
347     screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
348   }
349
350   screen_manager.run(context);
351 }
352
353 int
354 Main::run(int argc, char** argv)
355 {
356   int result = 0;
357
358   try
359   {
360     CommandLineArguments args;
361
362     try
363     {
364       args.parse_args(argc, argv);
365       g_log_level = args.get_log_level();
366     }
367     catch(const std::exception& err)
368     {
369       std::cout << "Error: " << err.what() << std::endl;
370       return EXIT_FAILURE;
371     }
372
373     PhysfsSubsystem physfs_subsystem(argv[0]);
374
375     timelog("config");
376     ConfigSubsystem config_subsystem;
377     args.merge_into(*g_config);
378
379     timelog("tinygettext");
380     init_tinygettext();
381
382     switch (args.get_action())
383     {
384       case CommandLineArguments::PRINT_VERSION:
385         args.print_version();
386         return 0;
387
388       case CommandLineArguments::PRINT_HELP:
389         args.print_help(argv[0]);
390         return 0;
391
392       case CommandLineArguments::PRINT_DATADIR:
393         args.print_datadir();
394         return 0;
395
396       default:
397         launch_game();
398         break;
399     }
400   }
401   catch(const std::exception& e)
402   {
403     log_fatal << "Unexpected exception: " << e.what() << std::endl;
404     result = 1;
405   }
406   catch(...)
407   {
408     log_fatal << "Unexpected exception" << std::endl;
409     result = 1;
410   }
411
412   g_dictionary_manager.reset();
413
414   return result;
415 }
416
417 /* EOF */