ddbac88b278d60b00d50228be8971bd5115424d4
[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 "supertux/game_manager.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/command_line_arguments.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 "video/lightmap.hpp"
54 #include "video/renderer.hpp"
55 #include "worldmap/worldmap.hpp"
56
57 namespace { DrawingContext *context_pointer; }
58
59 void
60 Main::init_config()
61 {
62   g_config = new Config();
63   try {
64     g_config->load();
65   } catch(std::exception& e) {
66     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
67   }
68 }
69
70 void
71 Main::init_tinygettext()
72 {
73   dictionary_manager = new tinygettext::DictionaryManager();
74   tinygettext::Log::set_log_info_callback(0);
75   dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
76
77   dictionary_manager->add_directory("locale");
78   dictionary_manager->set_charset("UTF-8");
79
80   // Config setting "locale" overrides language detection
81   if (g_config->locale != "")
82   {
83     dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
84   } else {
85     FL_Locale *locale;
86     FL_FindLocale(&locale);
87     tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
88     FL_FreeLocale(&locale);
89     dictionary_manager->set_language(language);
90   }
91 }
92
93 void
94 Main::init_physfs(const char* argv0)
95 {
96   if(!PHYSFS_init(argv0)) {
97     std::stringstream msg;
98     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
99     throw std::runtime_error(msg.str());
100   }
101
102   // allow symbolic links
103   PHYSFS_permitSymbolicLinks(1);
104
105   // Initialize physfs (this is a slightly modified version of
106   // PHYSFS_setSaneConfig)
107   const char *env_writedir;
108   std::string writedir;
109
110   if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
111     writedir = env_writedir;
112     if(!PHYSFS_setWriteDir(writedir.c_str())) {
113       std::ostringstream msg;
114       msg << "Failed to use configuration directory '"
115           <<  writedir << "': " << PHYSFS_getLastError();
116       throw std::runtime_error(msg.str());
117     }
118
119   } else {
120     std::string userdir = PHYSFS_getUserDir();
121
122     // Set configuration directory
123     writedir = userdir + WRITEDIR_NAME;
124     if(!PHYSFS_setWriteDir(writedir.c_str())) {
125       // try to create the directory
126       if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
127         std::ostringstream msg;
128         msg << "Failed creating configuration directory '"
129             << writedir << "': " << PHYSFS_getLastError();
130         throw std::runtime_error(msg.str());
131       }
132
133       if(!PHYSFS_setWriteDir(writedir.c_str())) {
134         std::ostringstream msg;
135         msg << "Failed to use configuration directory '"
136             <<  writedir << "': " << PHYSFS_getLastError();
137         throw std::runtime_error(msg.str());
138       }
139     }
140   }
141   PHYSFS_addToSearchPath(writedir.c_str(), 0);
142
143   // when started from source dir...
144   char* base_path = SDL_GetBasePath();
145   std::string dir = base_path;
146   SDL_free(base_path);
147
148   if (dir[dir.length() - 1] != '/')
149     dir += "/";
150   dir += "data";
151   std::string testfname = dir;
152   testfname += "/credits.txt";
153   bool sourcedir = false;
154   FILE* f = fopen(testfname.c_str(), "r");
155   if(f) {
156     fclose(f);
157     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
158       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
159     } else {
160       sourcedir = true;
161     }
162   }
163
164   if(!sourcedir) {
165     std::string datadir = PHYSFS_getBaseDir();
166     datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
167     datadir += "/" INSTALL_SUBDIR_SHARE;
168 #ifdef ENABLE_BINRELOC
169
170     char* dir;
171     br_init (NULL);
172     dir = br_find_data_dir(datadir.c_str());
173     datadir = dir;
174     free(dir);
175
176 #endif
177     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
178       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
179     }
180   }
181
182   //show search Path
183   char** searchpath = PHYSFS_getSearchPath();
184   for(char** i = searchpath; *i != NULL; i++)
185     log_info << "[" << *i << "] is in the search path" << std::endl;
186   PHYSFS_freeList(searchpath);
187 }
188
189 void
190 Main::init_sdl()
191 {
192   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
193     std::stringstream msg;
194     msg << "Couldn't initialize SDL: " << SDL_GetError();
195     throw std::runtime_error(msg.str());
196   }
197   // just to be sure
198   atexit(SDL_Quit);
199 }
200
201 void
202 Main::init_rand()
203 {
204   g_config->random_seed = gameRandom.srand(g_config->random_seed);
205
206   graphicsRandom.srand(0);
207
208   //const char *how = config->random_seed? ", user fixed.": ", from time().";
209   //log_info << "Using random seed " << config->random_seed << how << std::endl;
210 }
211
212 void
213 Main::init_video()
214 {
215   SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
216
217   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
218   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
219   if (!icon)
220   {
221     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
222   }
223   else
224   {
225     SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
226     SDL_FreeSurface(icon);
227   }
228   SDL_ShowCursor(0);
229
230   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
231            << " Window: "     << g_config->window_size
232            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
233            << " Area: "       << g_config->aspect_size << std::endl;
234 }
235
236 void
237 Main::init_audio()
238 {
239   sound_manager = new SoundManager();
240
241   sound_manager->enable_sound(g_config->sound_enabled);
242   sound_manager->enable_music(g_config->music_enabled);
243 }
244
245 void
246 Main::quit_audio()
247 {
248   if(sound_manager != NULL) {
249     delete sound_manager;
250     sound_manager = NULL;
251   }
252 }
253
254 static Uint32 last_timelog_ticks = 0;
255 static const char* last_timelog_component = 0;
256
257 static inline void timelog(const char* component)
258 {
259   Uint32 current_ticks = SDL_GetTicks();
260
261   if(last_timelog_component != 0) {
262     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
263   }
264
265   last_timelog_ticks = current_ticks;
266   last_timelog_component = component;
267 }
268
269 int
270 Main::run(int argc, char** argv)
271 {
272   int result = 0;
273
274   try
275   {
276     CommandLineArguments args;
277
278     // Do this before pre_parse_commandline, because --help now shows the
279     // default user data dir.
280     init_physfs(argv[0]);
281
282     try
283     {
284       args.parse_args(argc, argv);
285       g_log_level = args.get_log_level();
286     }
287     catch(const std::exception& err)
288     {
289       try
290       {
291         init_config();
292         args.merge_into(*g_config);
293         init_tinygettext();
294       }
295       catch(const std::exception& err)
296       {
297         log_fatal << "failed to init config or tinygettext: " << err.what() << std::endl;
298       }
299
300       std::cout << "Error: " << err.what() << std::endl;
301       return EXIT_FAILURE;
302     }
303
304     timelog("config");
305     init_config();
306     args.merge_into(*g_config);
307
308     timelog("tinygettext");
309     init_tinygettext();
310
311     switch (args.get_action())
312     {
313       case CommandLineArguments::PRINT_VERSION:
314         args.print_version();
315         return 0;
316
317       case CommandLineArguments::PRINT_HELP:
318         args.print_help(argv[0]);
319         return 0;
320
321       case CommandLineArguments::PRINT_DATADIR:
322         args.print_datadir();
323         return 0;
324
325       default:
326         // continue and start the game as usual
327         break;
328     }
329
330     init_sdl();
331     Console::instance = new Console();
332
333     timelog("controller");
334     g_input_manager = new InputManager();
335
336     timelog("commandline");
337
338     timelog("video");
339     std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
340     std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
341     DrawingContext context(*renderer, *lightmap);
342     context_pointer = &context;
343     init_video();
344
345     timelog("audio");
346     init_audio();
347
348     Console::instance->init_graphics();
349
350     timelog("scripting");
351     scripting::init_squirrel(g_config->enable_script_debugger);
352
353     timelog("resources");
354     Resources::load_shared();
355
356     timelog("addons");
357     AddonManager::get_instance().load_addons();
358
359     timelog(0);
360
361     const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
362
363     GameManager game_manager;
364     g_screen_manager = new ScreenManager();
365
366     init_rand();
367
368     if(g_config->start_level != "") {
369       // we have a normal path specified at commandline, not a physfs path.
370       // So we simply mount that path here...
371       std::string dir = FileSystem::dirname(g_config->start_level);
372       std::string fileProtocol = "file://";
373       std::string::size_type position = dir.find(fileProtocol);
374       if(position != std::string::npos) {
375         dir = dir.replace(position, fileProtocol.length(), "");
376       }
377       log_debug << "Adding dir: " << dir << std::endl;
378       PHYSFS_addToSearchPath(dir.c_str(), true);
379
380       if(g_config->start_level.size() > 4 &&
381          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
382         g_screen_manager->push_screen(std::unique_ptr<Screen>(
383                                         new worldmap::WorldMap(
384                                           FileSystem::basename(g_config->start_level), *default_savegame)));
385       } else {
386         std::unique_ptr<GameSession> session (
387           new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
388
389         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
390         init_rand();//initialise generator with seed from session
391
392         if(g_config->start_demo != "")
393           session->play_demo(g_config->start_demo);
394
395         if(g_config->record_demo != "")
396           session->record_demo(g_config->record_demo);
397         g_screen_manager->push_screen(std::move(session));
398       }
399     } else {
400       g_screen_manager->push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
401     }
402
403     g_screen_manager->run(context);
404   } catch(std::exception& e) {
405     log_fatal << "Unexpected exception: " << e.what() << std::endl;
406     result = 1;
407   } catch(...) {
408     log_fatal << "Unexpected exception" << std::endl;
409     result = 1;
410   }
411
412   delete g_screen_manager;
413   g_screen_manager = NULL;
414
415   Resources::unload_shared();
416   quit_audio();
417
418   if(g_config)
419     g_config->save();
420   delete g_config;
421   g_config = NULL;
422   delete g_input_manager;
423   g_input_manager = NULL;
424   delete Console::instance;
425   Console::instance = NULL;
426   scripting::exit_squirrel();
427   delete texture_manager;
428   texture_manager = NULL;
429   SDL_Quit();
430   PHYSFS_deinit();
431
432   delete dictionary_manager;
433   dictionary_manager = nullptr;
434
435   return result;
436 }
437
438 /* EOF */