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_mixer.h>
38 #include <SDL_image.h>
39 #include <SDL_opengl.h>
41 #include "gameconfig.hpp"
42 #include "resources.hpp"
43 #include "gettext.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "video/surface.hpp"
46 #include "video/texture_manager.hpp"
47 #include "control/joystickkeyboardcontroller.hpp"
50 #include "game_session.hpp"
51 #include "file_system.hpp"
52 #include "physfs/physfs_sdl.hpp"
53 #include "exceptions.hpp"
55 SDL_Surface* screen = 0;
56 JoystickKeyboardController* main_controller = 0;
57 TinyGetText::DictionaryManager dictionary_manager;
59 static void init_config()
61 config = new Config();
64 } catch(std::exception& e) {
66 std::cerr << "Couldn't load config file: " << e.what() << "\n";
71 static void init_tinygettext()
73 dictionary_manager.add_directory("locale");
74 dictionary_manager.set_charset("UTF-8");
77 static void init_physfs(const char* argv0)
79 if(!PHYSFS_init(argv0)) {
80 std::stringstream msg;
81 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
82 throw std::runtime_error(msg.str());
85 // Initialize physfs (this is a slightly modified version of
86 // PHYSFS_setSaneConfig
87 const char* application = PACKAGE_NAME;
88 const char* userdir = PHYSFS_getUserDir();
89 const char* dirsep = PHYSFS_getDirSeparator();
90 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
92 // Set configuration directory
93 sprintf(writedir, "%s.%s", userdir, application);
94 if(!PHYSFS_setWriteDir(writedir)) {
95 // try to create the directory
96 char* mkdir = new char[strlen(application) + 2];
97 sprintf(mkdir, ".%s", application);
98 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
99 std::ostringstream msg;
100 msg << "Failed creating configuration directory '"
101 << writedir << "': " << PHYSFS_getLastError();
104 throw std::runtime_error(msg.str());
108 if(!PHYSFS_setWriteDir(writedir)) {
109 std::ostringstream msg;
110 msg << "Failed to use configuration directory '"
111 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
116 PHYSFS_addToSearchPath(writedir, 0);
119 // Search for archives and add them to the search path
120 const char* archiveExt = "zip";
121 char** rc = PHYSFS_enumerateFiles("/");
122 size_t extlen = strlen(archiveExt);
124 for(char** i = rc; *i != 0; ++i) {
125 size_t l = strlen(*i);
126 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
127 const char* ext = (*i) + (l - extlen);
128 if(strcasecmp(ext, archiveExt) == 0) {
129 const char* d = PHYSFS_getRealDir(*i);
130 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
131 sprintf(str, "%s%s%s", d, dirsep, *i);
132 PHYSFS_addToSearchPath(str, 1);
140 // when started from source dir...
141 std::string dir = PHYSFS_getBaseDir();
143 std::string testfname = dir;
144 testfname += "/credits.txt";
145 bool sourcedir = false;
146 FILE* f = fopen(testfname.c_str(), "r");
149 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
150 std::cout << "Warning: Couldn't add '" << dir
151 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
158 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
160 #ifdef ENABLE_BINRELOC
161 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
165 datadir = APPDATADIR;
167 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
168 std::cout << "Couldn't add '" << datadir
169 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
174 // allow symbolic links
175 PHYSFS_permitSymbolicLinks(1);
178 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
179 printf("[%s] is in the search path.\n", *i);
182 static void print_usage(const char* argv0)
184 fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
187 " -f, --fullscreen Run in fullscreen mode\n"
188 " -w, --window Run in window mode\n"
189 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
190 " --disable-sfx Disable sound effects\n"
191 " --disable-music Disable music\n"
192 " --help Show this help message\n"
193 " --version Display SuperTux version and quit\n"
194 " --show-fps Display framerate in levels\n"
195 " --record-demo FILE LEVEL Record a demo to FILE\n"
196 " --play-demo FILE LEVEL Play a recorded demo\n"
200 static void parse_commandline(int argc, char** argv)
202 for(int i = 1; i < argc; ++i) {
203 std::string arg = argv[i];
205 if(arg == "--fullscreen" || arg == "-f") {
206 config->use_fullscreen = true;
207 } else if(arg == "--window" || arg == "-w") {
208 config->use_fullscreen = false;
209 } else if(arg == "--geometry" || arg == "-g") {
211 print_usage(argv[0]);
212 throw std::runtime_error("Need to specify a parameter for geometry switch");
214 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
216 print_usage(argv[0]);
217 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
219 } else if(arg == "--show-fps") {
220 config->show_fps = true;
221 } else if(arg == "--disable-sfx") {
222 config->sound_enabled = false;
223 } else if(arg == "--disable-music") {
224 config->music_enabled = false;
225 } else if(arg == "--play-demo") {
227 print_usage(argv[0]);
228 throw std::runtime_error("Need to specify a demo filename");
230 config->start_demo = argv[++i];
231 } else if(arg == "--record-demo") {
233 print_usage(argv[0]);
234 throw std::runtime_error("Need to specify a demo filename");
236 config->record_demo = argv[++i];
237 } else if(arg == "--help") {
238 print_usage(argv[0]);
239 throw graceful_shutdown();
240 } else if(arg == "--version") {
241 std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
242 throw graceful_shutdown();
243 } else if(arg[0] != '-') {
244 config->start_level = arg;
246 std::cerr << "Unknown option '" << arg << "'.\n";
247 std::cerr << "Use --help to see a list of options.\n";
251 // TODO joystick switchyes...
254 static void init_sdl()
256 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
257 std::stringstream msg;
258 msg << "Couldn't initialize SDL: " << SDL_GetError();
259 throw std::runtime_error(msg.str());
262 SDL_EnableUNICODE(1);
264 // wait 100ms and clear SDL event queue because sometimes we have random
265 // joystick events in the queue on startup...
268 while(SDL_PollEvent(&dummy))
272 static void check_gl_error()
274 GLenum glerror = glGetError();
275 std::string errormsg;
277 if(glerror != GL_NO_ERROR) {
279 case GL_INVALID_ENUM:
280 errormsg = "Invalid enumeration value";
282 case GL_INVALID_VALUE:
283 errormsg = "Numeric argzment out of range";
285 case GL_INVALID_OPERATION:
286 errormsg = "Invalid operation";
288 case GL_STACK_OVERFLOW:
289 errormsg = "stack overflow";
291 case GL_STACK_UNDERFLOW:
292 errormsg = "stack underflow";
294 case GL_OUT_OF_MEMORY:
295 errormsg = "out of memory";
297 case GL_TABLE_TOO_LARGE:
298 errormsg = "table too large";
301 errormsg = "unknown error number";
304 std::stringstream msg;
305 msg << "OpenGL Error: " << errormsg;
306 throw std::runtime_error(msg.str());
312 if(texture_manager != NULL)
313 texture_manager->save_textures();
315 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
316 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
317 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
318 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
320 int flags = SDL_OPENGL;
321 if(config->use_fullscreen)
322 flags |= SDL_FULLSCREEN;
323 int width = config->screenwidth;
324 int height = config->screenheight;
327 screen = SDL_SetVideoMode(width, height, bpp, flags);
329 std::stringstream msg;
330 msg << "Couldn't set video mode (" << width << "x" << height
331 << "-" << bpp << "bpp): " << SDL_GetError();
332 throw std::runtime_error(msg.str());
335 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
338 SDL_Surface* icon = IMG_Load_RW(
339 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
341 SDL_WM_SetIcon(icon, 0);
342 SDL_FreeSurface(icon);
346 std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
350 // setup opengl state and transform
351 glDisable(GL_DEPTH_TEST);
352 glDisable(GL_CULL_FACE);
353 glEnable(GL_TEXTURE_2D);
355 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
357 glViewport(0, 0, screen->w, screen->h);
358 glMatrixMode(GL_PROJECTION);
360 // logical resolution here not real monitor resolution
361 glOrtho(0, 800, 600, 0, -1.0, 1.0);
362 glMatrixMode(GL_MODELVIEW);
364 glTranslatef(0, 0, 0);
368 if(texture_manager != NULL)
369 texture_manager->reload_textures();
371 texture_manager = new TextureManager();
374 static void init_audio()
376 sound_manager = new SoundManager();
378 sound_manager->enable_sound(config->sound_enabled);
379 sound_manager->enable_music(config->music_enabled);
382 static void quit_audio()
385 delete sound_manager;
390 void wait_for_event(float min_delay, float max_delay)
392 assert(min_delay <= max_delay);
394 Uint32 min = (Uint32) (min_delay * 1000);
395 Uint32 max = (Uint32) (max_delay * 1000);
397 Uint32 ticks = SDL_GetTicks();
398 while(SDL_GetTicks() - ticks < min) {
400 sound_manager->update();
405 while (SDL_PollEvent(&event))
409 bool running = false;
410 ticks = SDL_GetTicks();
412 while(SDL_PollEvent(&event)) {
415 throw graceful_shutdown();
417 case SDL_JOYBUTTONDOWN:
418 case SDL_MOUSEBUTTONDOWN:
422 if(SDL_GetTicks() - ticks >= (max - min))
424 sound_manager->update();
429 int main(int argc, char** argv)
433 init_physfs(argv[0]);
435 main_controller = new JoystickKeyboardController();
438 parse_commandline(argc, argv);
444 if(config->start_level != "") {
445 // we have a normal path specified at commandline not physfs paths.
446 // So we simply mount that path here...
447 std::string dir = FileSystem::dirname(config->start_level);
448 PHYSFS_addToSearchPath(dir.c_str(), true);
450 FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
451 if(config->start_demo != "")
452 session.play_demo(config->start_demo);
453 if(config->record_demo != "")
454 session.record_demo(config->record_demo);
460 } catch(graceful_shutdown& e) {
461 } catch(std::exception& e) {
462 std::cerr << "Unexpected exception: " << e.what() << std::endl;
465 std::cerr << "Unexpected exception." << std::endl;
476 delete main_controller;
477 delete texture_manager;