4 // Copyright (C) 2005 Matthias Braun <matze@braunis.de>
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.
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.
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
31 #include <sys/types.h>
37 #include <SDL_image.h>
38 #include <SDL_opengl.h>
40 #include "gameconfig.hpp"
41 #include "resources.hpp"
42 #include "gettext.hpp"
43 #include "audio/sound_manager.hpp"
44 #include "video/surface.hpp"
45 #include "video/texture_manager.hpp"
46 #include "control/joystickkeyboardcontroller.hpp"
49 #include "game_session.hpp"
50 #include "file_system.hpp"
51 #include "physfs/physfs_sdl.hpp"
52 #include "exceptions.hpp"
54 SDL_Surface* screen = 0;
55 JoystickKeyboardController* main_controller = 0;
56 TinyGetText::DictionaryManager dictionary_manager;
58 static void init_config()
60 config = new Config();
63 } catch(std::exception& e) {
64 std::cerr << "Couldn't load config file: " << e.what() << "\n";
65 std::cerr << "Using default settings.\n";
69 static void init_tinygettext()
71 dictionary_manager.add_directory("locale");
72 dictionary_manager.set_charset("UTF-8");
75 static void init_physfs(const char* argv0)
77 if(!PHYSFS_init(argv0)) {
78 std::stringstream msg;
79 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
80 throw std::runtime_error(msg.str());
83 // Initialize physfs (this is a slightly modified version of
84 // PHYSFS_setSaneConfig
85 const char* application = PACKAGE_NAME;
86 const char* userdir = PHYSFS_getUserDir();
87 const char* dirsep = PHYSFS_getDirSeparator();
88 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
90 // Set configuration directory
91 sprintf(writedir, "%s.%s", userdir, application);
92 if(!PHYSFS_setWriteDir(writedir)) {
93 // try to create the directory
94 char* mkdir = new char[strlen(application) + 2];
95 sprintf(mkdir, ".%s", application);
96 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
97 std::ostringstream msg;
98 msg << "Failed creating configuration directory '"
99 << writedir << "': " << PHYSFS_getLastError();
102 throw std::runtime_error(msg.str());
106 if(!PHYSFS_setWriteDir(writedir)) {
107 std::ostringstream msg;
108 msg << "Failed to use configuration directory '"
109 << writedir << "': " << PHYSFS_getLastError();
111 throw std::runtime_error(msg.str());
114 PHYSFS_addToSearchPath(writedir, 0);
117 // Search for archives and add them to the search path
118 const char* archiveExt = "zip";
119 char** rc = PHYSFS_enumerateFiles("/");
120 size_t extlen = strlen(archiveExt);
122 for(char** i = rc; *i != 0; ++i) {
123 size_t l = strlen(*i);
124 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
125 const char* ext = (*i) + (l - extlen);
126 if(strcasecmp(ext, archiveExt) == 0) {
127 const char* d = PHYSFS_getRealDir(*i);
128 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
129 sprintf(str, "%s%s%s", d, dirsep, *i);
130 PHYSFS_addToSearchPath(str, 1);
138 // when started from source dir...
139 std::string dir = PHYSFS_getBaseDir();
141 std::string testfname = dir;
142 testfname += "/credits.txt";
143 bool sourcedir = false;
144 FILE* f = fopen(testfname.c_str(), "r");
147 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
148 std::cout << "Warning: Couldn't add '" << dir
149 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
156 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
158 #ifdef ENABLE_BINRELOC
159 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
163 datadir = APPDATADIR;
165 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
166 std::cout << "Couldn't add '" << datadir
167 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
172 // allow symbolic links
173 PHYSFS_permitSymbolicLinks(1);
176 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
177 printf("[%s] is in the search path.\n", *i);
180 static void print_usage(const char* argv0)
182 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
185 " -f, --fullscreen Run in fullscreen mode\n"
186 " -w, --window Run in window mode\n"
187 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
188 " --disable-sfx Disable sound effects\n"
189 " --disable-music Disable music\n"
190 " --help Show this help message\n"
191 " --version Display SuperTux version and quit\n"
192 " --show-fps Display framerate in levels\n"
193 " --record-demo FILE LEVEL Record a demo to FILE\n"
194 " --play-demo FILE LEVEL Play a recorded demo\n"
198 static void parse_commandline(int argc, char** argv)
200 for(int i = 1; i < argc; ++i) {
201 std::string arg = argv[i];
203 if(arg == "--fullscreen" || arg == "-f") {
204 config->use_fullscreen = true;
205 } else if(arg == "--window" || arg == "-w") {
206 config->use_fullscreen = false;
207 } else if(arg == "--geometry" || arg == "-g") {
209 print_usage(argv[0]);
210 throw std::runtime_error("Need to specify a parameter for geometry switch");
212 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
214 print_usage(argv[0]);
215 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
217 } else if(arg == "--show-fps") {
218 config->show_fps = true;
219 } else if(arg == "--disable-sfx") {
220 config->sound_enabled = false;
221 } else if(arg == "--disable-music") {
222 config->music_enabled = false;
223 } else if(arg == "--play-demo") {
225 print_usage(argv[0]);
226 throw std::runtime_error("Need to specify a demo filename");
228 config->start_demo = argv[++i];
229 } else if(arg == "--record-demo") {
231 print_usage(argv[0]);
232 throw std::runtime_error("Need to specify a demo filename");
234 config->record_demo = argv[++i];
235 } else if(arg == "--help") {
236 print_usage(argv[0]);
237 throw graceful_shutdown();
238 } else if(arg == "--version") {
239 std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
240 throw graceful_shutdown();
241 } else if(arg[0] != '-') {
242 config->start_level = arg;
244 std::cerr << "Unknown option '" << arg << "'.\n";
245 std::cerr << "Use --help to see a list of options.\n";
249 // TODO joystick switchyes...
252 static void init_sdl()
254 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
255 std::stringstream msg;
256 msg << "Couldn't initialize SDL: " << SDL_GetError();
257 throw std::runtime_error(msg.str());
260 SDL_EnableUNICODE(1);
262 // wait 100ms and clear SDL event queue because sometimes we have random
263 // joystick events in the queue on startup...
266 while(SDL_PollEvent(&dummy))
270 static void check_gl_error()
272 GLenum glerror = glGetError();
273 std::string errormsg;
275 if(glerror != GL_NO_ERROR) {
277 case GL_INVALID_ENUM:
278 errormsg = "Invalid enumeration value";
280 case GL_INVALID_VALUE:
281 errormsg = "Numeric argzment out of range";
283 case GL_INVALID_OPERATION:
284 errormsg = "Invalid operation";
286 case GL_STACK_OVERFLOW:
287 errormsg = "stack overflow";
289 case GL_STACK_UNDERFLOW:
290 errormsg = "stack underflow";
292 case GL_OUT_OF_MEMORY:
293 errormsg = "out of memory";
295 case GL_TABLE_TOO_LARGE:
296 errormsg = "table too large";
299 errormsg = "unknown error number";
302 std::stringstream msg;
303 msg << "OpenGL Error: " << errormsg;
304 throw std::runtime_error(msg.str());
310 if(texture_manager != NULL)
311 texture_manager->save_textures();
313 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
314 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
315 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
316 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
318 int flags = SDL_OPENGL;
319 if(config->use_fullscreen)
320 flags |= SDL_FULLSCREEN;
321 int width = config->screenwidth;
322 int height = config->screenheight;
325 screen = SDL_SetVideoMode(width, height, bpp, flags);
327 std::stringstream msg;
328 msg << "Couldn't set video mode (" << width << "x" << height
329 << "-" << bpp << "bpp): " << SDL_GetError();
330 throw std::runtime_error(msg.str());
333 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
336 SDL_Surface* icon = IMG_Load_RW(
337 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
339 SDL_WM_SetIcon(icon, 0);
340 SDL_FreeSurface(icon);
344 std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
348 // setup opengl state and transform
349 glDisable(GL_DEPTH_TEST);
350 glDisable(GL_CULL_FACE);
351 glEnable(GL_TEXTURE_2D);
353 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
355 glViewport(0, 0, screen->w, screen->h);
356 glMatrixMode(GL_PROJECTION);
358 // logical resolution here not real monitor resolution
359 glOrtho(0, 800, 600, 0, -1.0, 1.0);
360 glMatrixMode(GL_MODELVIEW);
362 glTranslatef(0, 0, 0);
366 if(texture_manager != NULL)
367 texture_manager->reload_textures();
369 texture_manager = new TextureManager();
372 static void init_audio()
374 sound_manager = new SoundManager();
376 sound_manager->enable_sound(config->sound_enabled);
377 sound_manager->enable_music(config->music_enabled);
380 static void quit_audio()
383 delete sound_manager;
388 void wait_for_event(float min_delay, float max_delay)
390 assert(min_delay <= max_delay);
392 Uint32 min = (Uint32) (min_delay * 1000);
393 Uint32 max = (Uint32) (max_delay * 1000);
395 Uint32 ticks = SDL_GetTicks();
396 while(SDL_GetTicks() - ticks < min) {
398 sound_manager->update();
403 while (SDL_PollEvent(&event))
407 bool running = false;
408 ticks = SDL_GetTicks();
410 while(SDL_PollEvent(&event)) {
413 throw graceful_shutdown();
415 case SDL_JOYBUTTONDOWN:
416 case SDL_MOUSEBUTTONDOWN:
420 if(SDL_GetTicks() - ticks >= (max - min))
422 sound_manager->update();
428 static Uint32 last_timelog_ticks = 0;
429 static const char* last_timelog_component = 0;
431 static inline void timelog(const char* component)
433 Uint32 current_ticks = SDL_GetTicks();
435 if(last_timelog_component != 0) {
436 printf("Component '%s' finished after %f seconds\n",
437 last_timelog_component, (current_ticks - last_timelog_ticks) / 1000.0);
440 last_timelog_ticks = current_ticks;
441 last_timelog_component = component;
444 static inline void timelog(const char* )
449 int main(int argc, char** argv)
453 init_physfs(argv[0]);
455 timelog("controller");
456 main_controller = new JoystickKeyboardController();
459 timelog("tinygettext");
461 timelog("commandline");
462 parse_commandline(argc, argv);
470 timelog("resources");
473 if(config->start_level != "") {
474 // we have a normal path specified at commandline not physfs paths.
475 // So we simply mount that path here...
476 std::string dir = FileSystem::dirname(config->start_level);
477 PHYSFS_addToSearchPath(dir.c_str(), true);
479 FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
480 if(config->start_demo != "")
481 session.play_demo(config->start_demo);
482 if(config->record_demo != "")
483 session.record_demo(config->record_demo);
489 } catch(graceful_shutdown& e) {
490 } catch(std::exception& e) {
491 std::cerr << "Unexpected exception: " << e.what() << std::endl;
494 std::cerr << "Unexpected exception." << std::endl;
505 delete main_controller;
506 delete texture_manager;