Fix curl include paths that were messed up in 5778. The other part of the fix a C...
[supertux.git] / src / main.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "log.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <physfs.h>
34 #include <SDL.h>
35 #include <SDL_image.h>
36
37 #ifdef MACOSX
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
40 }
41 #endif
42
43 #include "gameconfig.hpp"
44 #include "resources.hpp"
45 #include "gettext.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "video/surface.hpp"
48 #include "video/texture_manager.hpp"
49 #include "video/drawing_context.hpp"
50 #include "video/glutil.hpp"
51 #include "control/joystickkeyboardcontroller.hpp"
52 #include "options_menu.hpp"
53 #include "mainloop.hpp"
54 #include "title.hpp"
55 #include "game_session.hpp"
56 #include "scripting/level.hpp"
57 #include "scripting/squirrel_util.hpp"
58 #include "file_system.hpp"
59 #include "physfs/physfs_sdl.hpp"
60 #include "random_generator.hpp"
61 #include "worldmap/worldmap.hpp"
62 #include "addon/addon_manager.hpp"
63 #include "binreloc/binreloc.h"
64
65 namespace { DrawingContext *context_pointer; }
66 SDL_Surface *screen;
67 JoystickKeyboardController* main_controller = 0;
68 TinyGetText::DictionaryManager dictionary_manager;
69
70 int SCREEN_WIDTH;
71 int SCREEN_HEIGHT;
72
73 static void init_config()
74 {
75   config = new Config();
76   try {
77     config->load();
78   } catch(std::exception& e) {
79     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
80   }
81 }
82
83 static void init_tinygettext()
84 {
85   dictionary_manager.add_directory("locale");
86   dictionary_manager.set_charset("UTF-8");
87
88   // Config setting "locale" overrides language detection
89   if (config->locale != "") {
90     dictionary_manager.set_language( config->locale );
91   }
92 }
93
94 static void 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* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
108   const char* userdir = PHYSFS_getUserDir();
109   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
110
111   // Set configuration directory
112   sprintf(writedir, "%s.%s", userdir, application);
113   if(!PHYSFS_setWriteDir(writedir)) {
114     // try to create the directory
115     char* mkdir = new char[strlen(application) + 2];
116     sprintf(mkdir, ".%s", application);
117     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
118       std::ostringstream msg;
119       msg << "Failed creating configuration directory '"
120           << writedir << "': " << PHYSFS_getLastError();
121       delete[] writedir;
122       delete[] mkdir;
123       throw std::runtime_error(msg.str());
124     }
125     delete[] mkdir;
126
127     if(!PHYSFS_setWriteDir(writedir)) {
128       std::ostringstream msg;
129       msg << "Failed to use configuration directory '"
130           <<  writedir << "': " << PHYSFS_getLastError();
131       delete[] writedir;
132       throw std::runtime_error(msg.str());
133     }
134   }
135   PHYSFS_addToSearchPath(writedir, 0);
136   delete[] writedir;
137
138   // when started from source dir...
139   std::string dir = PHYSFS_getBaseDir();
140   dir += "/data";
141   std::string testfname = dir;
142   testfname += "/credits.txt";
143   bool sourcedir = false;
144   FILE* f = fopen(testfname.c_str(), "r");
145   if(f) {
146     fclose(f);
147     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
148       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
149     } else {
150       sourcedir = true;
151     }
152   }
153
154 #ifdef MACOSX
155 {
156   using namespace supertux_apple;
157
158   // when started from Application file on Mac OS X...
159   char path[PATH_MAX];
160   CFBundleRef mainBundle = CFBundleGetMainBundle();
161   assert(mainBundle != 0);
162   CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
163   assert(mainBundleURL != 0);
164   CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
165   assert(pathStr != 0);
166   CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
167   CFRelease(mainBundleURL);
168   CFRelease(pathStr);
169
170   dir = std::string(path) + "/Contents/Resources/data";
171   testfname = dir + "/credits.txt";
172   sourcedir = false;
173   f = fopen(testfname.c_str(), "r");
174   if(f) {
175     fclose(f);
176     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
177       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
178     } else {
179       sourcedir = true;
180     }
181   }
182 }
183 #endif
184
185 #ifdef _WIN32
186   PHYSFS_addToSearchPath(".\\data", 1);
187 #endif
188
189   if(!sourcedir) {
190 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
191     std::string datadir;
192 #ifdef ENABLE_BINRELOC
193
194     char* dir;
195     br_init (NULL);
196     dir = br_find_data_dir(APPDATADIR);
197     datadir = dir;
198     free(dir);
199
200 #else
201     datadir = APPDATADIR;
202 #endif
203     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
204       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
205     }
206 #endif
207   }
208
209   //show search Path
210   char** searchpath = PHYSFS_getSearchPath();
211   for(char** i = searchpath; *i != NULL; i++)
212     log_info << "[" << *i << "] is in the search path" << std::endl;
213   PHYSFS_freeList(searchpath);
214 }
215
216 static void print_usage(const char* argv0)
217 {
218   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
219   fprintf(stderr,
220           _("Options:\n"
221             "  -f, --fullscreen             Run in fullscreen mode\n"
222             "  -w, --window                 Run in window mode\n"
223             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
224             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
225             "  -d, --default                Reset video settings to default values\n"
226             "  --disable-sfx                Disable sound effects\n"
227             "  --disable-music              Disable music\n"
228             "  -h, --help                   Show this help message\n"
229             "  -v, --version                Show SuperTux version and quit\n"
230             "  --console                    Enable ingame scripting console\n"
231             "  --noconsole                  Disable ingame scripting console\n"
232             "  --show-fps                   Display framerate in levels\n"
233             "  --no-show-fps                Do not display framerate in levels\n"
234             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
235             "  --play-demo FILE LEVEL       Play a recorded demo\n"
236             "  -s, --debug-scripts          Enable script debugger.\n"
237             "\n"));
238 }
239
240 /**
241  * Options that should be evaluated prior to any initializations at all go here
242  */
243 static bool pre_parse_commandline(int argc, char** argv)
244 {
245   for(int i = 1; i < argc; ++i) {
246     std::string arg = argv[i];
247
248     if(arg == "--version" || arg == "-v") {
249       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
250       return true;
251     }
252   }
253
254   return false;
255 }
256
257 /**
258  * Options that should be evaluated after config is read go here
259  */
260 static bool parse_commandline(int argc, char** argv)
261 {
262   for(int i = 1; i < argc; ++i) {
263     std::string arg = argv[i];
264
265     if(arg == "--help" || arg == "-h") {
266       print_usage(argv[0]);
267       return true;
268     } else if(arg == "--fullscreen" || arg == "-f") {
269       config->use_fullscreen = true;
270     } else if(arg == "--default" || arg == "-d") {
271       config->use_fullscreen = false;
272       
273       config->window_width  = 800;
274       config->window_height = 600;
275
276       config->fullscreen_width  = 800;
277       config->fullscreen_height = 600;
278
279       config->aspect_width  = 0;  // auto detect
280       config->aspect_height = 0;
281       
282     } else if(arg == "--window" || arg == "-w") {
283       config->use_fullscreen = false;
284     } else if(arg == "--geometry" || arg == "-g") {
285       i += 1;
286       if(i >= argc) 
287         {
288           print_usage(argv[0]);
289           throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
290         } 
291       else 
292         {
293           int width, height;
294           if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
295             {
296               print_usage(argv[0]);
297               throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
298             }
299           else
300             {
301               config->window_width  = width;
302               config->window_height = height;
303
304               config->fullscreen_width  = width;
305               config->fullscreen_height = height;
306             }
307         }
308     } else if(arg == "--aspect" || arg == "-a") {
309       i += 1;
310       if(i >= argc) 
311         {
312           print_usage(argv[0]);
313           throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
314         } 
315       else 
316         {
317           int aspect_width  = 0;
318           int aspect_height = 0;
319           if (strcmp(argv[i], "auto") == 0)
320             {
321               aspect_width  = 0;
322               aspect_height = 0;
323             }
324           else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
325             {
326               print_usage(argv[0]);
327               throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
328             }
329           else 
330             {
331               float aspect_ratio = static_cast<double>(config->aspect_width) /
332                 static_cast<double>(config->aspect_height);
333
334               // use aspect ratio to calculate logical resolution
335               if (aspect_ratio > 1) {
336                 config->aspect_width  = static_cast<int> (600 * aspect_ratio + 0.5);
337                 config->aspect_height = 600;
338               } else {
339                 config->aspect_width  = 600;
340                 config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
341               }
342             }
343         }
344     } else if(arg == "--show-fps") {
345       config->show_fps = true;
346     } else if(arg == "--no-show-fps") {
347       config->show_fps = false;
348     } else if(arg == "--console") {
349       config->console_enabled = true;
350     } else if(arg == "--noconsole") {
351       config->console_enabled = false;
352     } else if(arg == "--disable-sfx") {
353       config->sound_enabled = false;
354     } else if(arg == "--disable-music") {
355       config->music_enabled = false;
356     } else if(arg == "--play-demo") {
357       if(i+1 >= argc) {
358         print_usage(argv[0]);
359         throw std::runtime_error("Need to specify a demo filename");
360       }
361       config->start_demo = argv[++i];
362     } else if(arg == "--record-demo") {
363       if(i+1 >= argc) {
364         print_usage(argv[0]);
365         throw std::runtime_error("Need to specify a demo filename");
366       }
367       config->record_demo = argv[++i];
368     } else if(arg == "--debug-scripts" || arg == "-s") {
369       config->enable_script_debugger = true;
370     } else if(arg[0] != '-') {
371       config->start_level = arg;
372     } else {
373       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
374       return true;
375     }
376   }
377
378   return false;
379 }
380
381 static void init_sdl()
382 {
383   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
384     std::stringstream msg;
385     msg << "Couldn't initialize SDL: " << SDL_GetError();
386     throw std::runtime_error(msg.str());
387   }
388   // just to be sure
389   atexit(SDL_Quit);
390
391   SDL_EnableUNICODE(1);
392
393   // wait 100ms and clear SDL event queue because sometimes we have random
394   // joystick events in the queue on startup...
395   SDL_Delay(100);
396   SDL_Event dummy;
397   while(SDL_PollEvent(&dummy))
398       ;
399 }
400
401 static void init_rand()
402 {
403   config->random_seed = systemRandom.srand(config->random_seed);
404
405   //const char *how = config->random_seed? ", user fixed.": ", from time().";
406   //log_info << "Using random seed " << config->random_seed << how << std::endl;
407 }
408
409 void init_video()
410 {
411   // FIXME: Add something here
412   SCREEN_WIDTH  = 800;
413   SCREEN_HEIGHT = 600;
414
415   context_pointer->init_renderer();
416   screen = SDL_GetVideoSurface();
417
418   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
419
420   // set icon
421 #ifdef MACOSX
422   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
423 #else
424   const char* icon_fname = "images/engine/icons/supertux.xpm";
425 #endif
426   SDL_Surface* icon;
427   try {
428     icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
429   } catch (const std::runtime_error& err) {
430     icon = 0;
431     log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
432   }
433   if(icon != 0) {
434     SDL_WM_SetIcon(icon, 0);
435     SDL_FreeSurface(icon);
436   }
437 #ifdef DEBUG
438   else {
439     log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
440   }
441 #endif
442
443   SDL_ShowCursor(0);
444
445   log_info << (config->use_fullscreen?"fullscreen ":"window ")
446            << " Window: "     << config->window_width     << "x" << config->window_height
447            << " Fullscreen: " << config->fullscreen_width << "x" << config->fullscreen_height
448            << " Area: "       << config->aspect_width     << "x" << config->aspect_height << std::endl;
449 }
450
451 static void init_audio()
452 {
453   sound_manager = new SoundManager();
454
455   sound_manager->enable_sound(config->sound_enabled);
456   sound_manager->enable_music(config->music_enabled);
457 }
458
459 static void quit_audio()
460 {
461   if(sound_manager != NULL) {
462     delete sound_manager;
463     sound_manager = NULL;
464   }
465 }
466
467 void wait_for_event(float min_delay, float max_delay)
468 {
469   assert(min_delay <= max_delay);
470
471   Uint32 min = (Uint32) (min_delay * 1000);
472   Uint32 max = (Uint32) (max_delay * 1000);
473
474   Uint32 ticks = SDL_GetTicks();
475   while(SDL_GetTicks() - ticks < min) {
476     SDL_Delay(10);
477     sound_manager->update();
478   }
479
480   // clear event queue
481   SDL_Event event;
482   while (SDL_PollEvent(&event))
483   {}
484
485   /* Handle events: */
486   bool running = false;
487   ticks = SDL_GetTicks();
488   while(running) {
489     while(SDL_PollEvent(&event)) {
490       switch(event.type) {
491         case SDL_QUIT:
492           main_loop->quit();
493           break;
494         case SDL_KEYDOWN:
495         case SDL_JOYBUTTONDOWN:
496         case SDL_MOUSEBUTTONDOWN:
497           running = false;
498       }
499     }
500     if(SDL_GetTicks() - ticks >= (max - min))
501       running = false;
502     sound_manager->update();
503     SDL_Delay(10);
504   }
505 }
506
507 #ifdef DEBUG
508 static Uint32 last_timelog_ticks = 0;
509 static const char* last_timelog_component = 0;
510
511 static inline void timelog(const char* component)
512 {
513   Uint32 current_ticks = SDL_GetTicks();
514
515   if(last_timelog_component != 0) {
516     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
517   }
518
519   last_timelog_ticks = current_ticks;
520   last_timelog_component = component;
521 }
522 #else
523 static inline void timelog(const char* )
524 {
525 }
526 #endif
527
528 int main(int argc, char** argv)
529 {
530   int result = 0;
531
532 #ifndef DEBUG
533   try {
534 #endif
535
536     if(pre_parse_commandline(argc, argv))
537       return 0;
538
539     Console::instance = new Console();
540     init_physfs(argv[0]);
541     init_sdl();
542
543     timelog("controller");
544     main_controller = new JoystickKeyboardController();
545
546     timelog("config");
547     init_config();
548
549     timelog("addons");
550     AddonManager::get_instance().load_addons();
551
552     timelog("tinygettext");
553     init_tinygettext();
554
555     timelog("commandline");
556     if(parse_commandline(argc, argv))
557       return 0;
558
559     timelog("audio");
560     init_audio();
561
562     timelog("video");
563     DrawingContext context;
564     context_pointer = &context;
565     init_video();
566
567     Console::instance->init_graphics();
568
569     timelog("scripting");
570     Scripting::init_squirrel(config->enable_script_debugger);
571
572     timelog("resources");
573     load_shared();
574
575     timelog(0);
576
577     main_loop = new MainLoop();
578     if(config->start_level != "") {
579       // we have a normal path specified at commandline not physfs paths.
580       // So we simply mount that path here...
581       std::string dir = FileSystem::dirname(config->start_level);
582       PHYSFS_addToSearchPath(dir.c_str(), true);
583
584       if(config->start_level.size() > 4 &&
585               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
586           init_rand();
587           main_loop->push_screen(new WorldMapNS::WorldMap(
588                       FileSystem::basename(config->start_level)));
589       } else {
590         init_rand();//If level uses random eg. for
591         // rain particles before we do this:
592         std::auto_ptr<GameSession> session (
593                 new GameSession(FileSystem::basename(config->start_level)));
594
595         config->random_seed =session->get_demo_random_seed(config->start_demo);
596         init_rand();//initialise generator with seed from session
597
598         if(config->start_demo != "")
599           session->play_demo(config->start_demo);
600
601         if(config->record_demo != "")
602           session->record_demo(config->record_demo);
603         main_loop->push_screen(session.release());
604       }
605     } else {
606       init_rand();
607       main_loop->push_screen(new TitleScreen());
608     }
609
610     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
611     main_loop->run(context);
612 #ifndef DEBUG
613   } catch(std::exception& e) {
614     log_fatal << "Unexpected exception: " << e.what() << std::endl;
615     result = 1;
616   } catch(...) {
617     log_fatal << "Unexpected exception" << std::endl;
618     result = 1;
619   }
620 #endif
621
622   delete main_loop;
623   main_loop = NULL;
624
625   unload_shared();
626   quit_audio();
627
628   if(config)
629     config->save();
630   delete config;
631   config = NULL;
632   delete main_controller;
633   main_controller = NULL;
634   delete Console::instance;
635   Console::instance = NULL;
636   Scripting::exit_squirrel();
637   delete texture_manager;
638   texture_manager = NULL;
639   SDL_Quit();
640   PHYSFS_deinit();
641
642   return result;
643 }