add a followviewport bool to uncontrolled_sounds, so that the c1 music doesn't get...
[openc2e.git] / Engine.cpp
blobe56a01e612c7c80bbdcb7ce1ed095930a80ec3b7
1 /*
2 * Engine.cpp
3 * openc2e
5 * Created by Alyssa Milburn on Tue Nov 28 2006.
6 * Copyright (c) 2006-2008 Alyssa Milburn. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
20 #include "Room.h"
21 #include "Engine.h"
22 #include "World.h"
23 #include "MetaRoom.h"
24 #include "caosVM.h" // for setupCommandPointers()
25 #include "caosScript.h" // for executeNetwork()
26 #include "PointerAgent.h"
27 #include "dialect.h" // registerDelegates
28 #include "NullBackend.h"
29 #include "NullAudioBackend.h"
31 #include <boost/filesystem/path.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/convenience.hpp>
34 #include <boost/program_options.hpp>
35 #include <boost/format.hpp>
36 namespace fs = boost::filesystem;
37 namespace po = boost::program_options;
39 #ifndef _WIN32
40 #include <sys/types.h> // passwd*
41 #include <pwd.h> // getpwuid
42 #endif
44 #ifdef _WIN32
45 #include <shlobj.h>
46 #endif
48 Engine engine;
50 Engine::Engine() {
51 done = false;
52 dorendering = true;
53 fastticks = false;
54 refreshdisplay = false;
56 bmprenderer = false;
58 tickdata = 0;
59 for (unsigned int i = 0; i < 10; i++) ticktimes[i] = 0;
60 ticktimeptr = 0;
61 version = 0; // TODO: something something
63 srand(time(NULL)); // good a place as any :)
65 cmdline_enable_sound = true;
66 cmdline_norun = false;
68 palette = 0;
70 addPossibleBackend("null", shared_ptr<Backend>(new NullBackend()));
71 addPossibleAudioBackend("null", shared_ptr<AudioBackend>(new NullAudioBackend()));
74 Engine::~Engine() {
77 void Engine::addPossibleBackend(std::string s, boost::shared_ptr<Backend> b) {
78 assert(!backend);
79 assert(b);
80 preferred_backend = s;
81 possible_backends[s] = b;
84 void Engine::addPossibleAudioBackend(std::string s, boost::shared_ptr<AudioBackend> b) {
85 assert(!audio);
86 assert(b);
87 preferred_audiobackend = s;
88 possible_audiobackends[s] = b;
91 void Engine::setBackend(shared_ptr<Backend> b) {
92 backend = b;
93 lasttimestamp = backend->ticks();
95 // load palette for C1
96 if (world.gametype == "c1") {
97 // TODO: case-sensitivity for the lose
98 fs::path palpath(world.data_directories[0] / "/Palettes/palette.dta");
99 if (fs::exists(palpath) && !fs::is_directory(palpath)) {
100 palette = new unsigned char[768];
102 std::ifstream f(palpath.native_directory_string().c_str(), std::ios::binary);
103 f >> std::noskipws;
104 f.read((char *)palette, 768);
106 for (unsigned int i = 0; i < 768; i++) {
107 palette[i] = palette[i] * 4;
110 backend->setPalette((uint8 *)palette);
111 } else
112 throw creaturesException("Couldn't find C1 palette data!");
116 std::string Engine::executeNetwork(std::string in) {
117 // now parse and execute the CAOS we obtained
118 caosVM vm(0); // needs to be outside 'try' so we can reset outputstream on exception
119 try {
120 std::istringstream s(in);
121 caosScript script(world.gametype, "<network>"); // XXX
122 script.parse(s);
123 script.installScripts();
124 std::ostringstream o;
125 vm.setOutputStream(o);
126 vm.runEntirely(script.installer);
127 vm.outputstream = 0; // otherwise would point to dead stack
128 return o.str();
129 } catch (std::exception &e) {
130 vm.outputstream = 0; // otherwise would point to dead stack
131 return std::string("### EXCEPTION: ") + e.what();
135 bool Engine::needsUpdate() {
136 return (!world.paused) && (fastticks || (backend->ticks() > (tickdata + world.ticktime)));
139 void Engine::update() {
140 tickdata = backend->ticks();
142 // tick the world
143 world.tick();
145 // draw the world
146 if (dorendering || refreshdisplay) {
147 refreshdisplay = false;
149 if (backend->selfRender()) {
150 // TODO: this makes race/pace hilariously inaccurate, since render time isn't included
151 backend->requestRender();
152 } else {
153 world.drawWorld();
157 // play C1 music
158 // TODO: this doesn't seem to actually be every 7 seconds, but actually somewhat random
159 // TODO: this should be linked to 'real' time, so it doesn't go crazy when game speed is modified
160 // TODO: is this the right place for this?
161 if (version == 1 && (world.tickcount % 70) == 0) {
162 int piece = 1 + (rand() % 28);
163 std::string filename = boost::str(boost::format("MU%02d") % piece);
164 boost::shared_ptr<AudioSource> s = world.playAudio(filename, AgentRef(), false, false, true);
165 if (s) s->setVolume(0.4f);
168 // update our data for things like pace, race, ticktime, etc
169 ticktimes[ticktimeptr] = backend->ticks() - tickdata;
170 ticktimeptr++;
171 if (ticktimeptr == 10) ticktimeptr = 0;
172 float avgtime = 0;
173 for (unsigned int i = 0; i < 10; i++) avgtime += ((float)ticktimes[i] / world.ticktime);
174 world.pace = avgtime / 10;
176 world.race = backend->ticks() - lasttimestamp;
177 lasttimestamp = backend->ticks();
180 bool Engine::tick() {
181 assert(backend);
182 backend->handleEvents();
184 // tick+draw the world, if necessary
185 bool needupdate = needsUpdate();
186 if (needupdate)
187 update();
189 processEvents();
190 if (needupdate)
191 handleKeyboardScrolling();
193 return needupdate;
196 void Engine::handleKeyboardScrolling() {
197 // keyboard-based scrolling
198 static float accelspeed = 8, decelspeed = .5, maxspeed = 64;
199 static float velx = 0;
200 static float vely = 0;
202 bool wasdMode = false;
203 caosVar v = world.variables["engine_wasd"];
204 if (v.hasInt()) {
205 switch (v.getInt()) {
206 case 1: // enable if CTRL is held
207 wasdMode = backend->keyDown(17); // CTRL
208 break;
209 case 2: // enable unconditionally
210 // (this needs agent support to suppress chat bubbles etc)
211 wasdMode = true;
212 break;
213 case 0: // disable
214 wasdMode = false;
215 break;
216 default: // disable
217 std::cout << "Warning: engine_wasd_scrolling is set to unknown value " << v.getInt() << std::endl;
218 world.variables["engine_wasd_scrolling"] = caosVar(0);
219 wasdMode = false;
220 break;
224 // check keys
225 bool leftdown = backend->keyDown(37)
226 || (wasdMode && a_down);
227 bool rightdown = backend->keyDown(39)
228 || (wasdMode && d_down);
229 bool updown = backend->keyDown(38)
230 || (wasdMode && w_down);
231 bool downdown = backend->keyDown(40)
232 || (wasdMode && s_down);
234 if (leftdown)
235 velx -= accelspeed;
236 if (rightdown)
237 velx += accelspeed;
238 if (!leftdown && !rightdown) {
239 velx *= decelspeed;
240 if (fabs(velx) < 0.1) velx = 0;
242 if (updown)
243 vely -= accelspeed;
244 if (downdown)
245 vely += accelspeed;
246 if (!updown && !downdown) {
247 vely *= decelspeed;
248 if (fabs(vely) < 0.1) vely = 0;
251 // enforced maximum speed
252 if (velx >= maxspeed) velx = maxspeed;
253 else if (velx <= -maxspeed) velx = -maxspeed;
254 if (vely >= maxspeed) vely = maxspeed;
255 else if (vely <= -maxspeed) vely = -maxspeed;
257 // do the actual movement
258 if (velx || vely) {
259 int adjustx = world.camera.getX(), adjusty = world.camera.getY();
260 int adjustbyx = (int)velx, adjustbyy = (int) vely;
262 world.camera.moveTo(adjustx + adjustbyx, adjusty + adjustbyy, jump);
266 void Engine::processEvents() {
267 SomeEvent event;
268 while (backend->pollEvent(event)) {
269 switch (event.type) {
270 case eventresizewindow:
271 handleResizedWindow(event);
272 break;
274 case eventmousemove:
275 handleMouseMove(event);
276 break;
278 case eventmousebuttonup:
279 case eventmousebuttondown:
280 handleMouseButton(event);
281 break;
283 case eventkeydown:
284 handleKeyDown(event);
285 break;
287 case eventspecialkeydown:
288 handleSpecialKeyDown(event);
289 break;
291 case eventspecialkeyup:
292 handleSpecialKeyUp(event);
293 break;
295 case eventquit:
296 done = true;
297 break;
299 default:
300 break;
305 void Engine::handleResizedWindow(SomeEvent &event) {
306 // notify agents
307 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
308 if (!*i) continue;
309 (*i)->queueScript(123, 0); // window resized script
313 void Engine::handleMouseMove(SomeEvent &event) {
314 // move the cursor
315 world.hand()->handleEvent(event);
317 // notify agents
318 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
319 if (!*i) continue;
320 if ((*i)->imsk_mouse_move) {
321 caosVar x; x.setFloat(world.hand()->x);
322 caosVar y; y.setFloat(world.hand()->y);
323 (*i)->queueScript(75, 0, x, y); // Raw Mouse Move
328 void Engine::handleMouseButton(SomeEvent &event) {
329 // notify agents
330 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
331 if (!*i) continue;
332 if ((event.type == eventmousebuttonup && (*i)->imsk_mouse_up) ||
333 (event.type == eventmousebuttondown && (*i)->imsk_mouse_down)) {
334 // set the button value as necessary
335 caosVar button;
336 switch (event.button) { // Backend guarantees that only one button will be set on a mousebuttondown event.
337 // the values here make fuzzie suspicious that c2e combines these events
338 // nornagon seems to think c2e doesn't
339 case buttonleft: button.setInt(1); break;
340 case buttonright: button.setInt(2); break;
341 case buttonmiddle: button.setInt(4); break;
342 default: break;
345 // if it was a mouse button we're interested in, then fire the relevant raw event
346 if (button.getInt() != 0) {
347 if (event.type == eventmousebuttonup)
348 (*i)->queueScript(77, 0, button); // Raw Mouse Up
349 else
350 (*i)->queueScript(76, 0, button); // Raw Mouse Down
353 if ((event.type == eventmousebuttondown &&
354 (event.button == buttonwheelup || event.button == buttonwheeldown) &&
355 (*i)->imsk_mouse_wheel)) {
356 // fire the mouse wheel event with the relevant delta value
357 caosVar delta;
358 if (event.button == buttonwheeldown)
359 delta.setInt(-120);
360 else
361 delta.setInt(120);
362 (*i)->queueScript(78, 0, delta); // Raw Mouse Wheel
366 world.hand()->handleEvent(event);
369 void Engine::handleKeyDown(SomeEvent &event) {
370 switch (event.key) {
371 case 'w': w_down = true; break;
372 case 'a': a_down = true; break;
373 case 's': s_down = true; break;
374 case 'd': d_down = true; break;
377 // tell the agent with keyboard focus
378 if (world.focusagent) {
379 TextEntryPart *t = (TextEntryPart *)((CompoundAgent *)world.focusagent.get())->part(world.focuspart);
380 if (t)
381 t->handleKey(event.key);
384 // notify agents
385 caosVar k;
386 k.setInt(event.key);
387 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
388 if (!*i) continue;
389 if ((*i)->imsk_translated_char)
390 (*i)->queueScript(79, 0, k); // translated char script
394 void Engine::handleSpecialKeyUp(SomeEvent &event) {
395 switch (event.key) {
396 case 0x57:
397 w_down = false;
398 break;
399 case 0x41:
400 a_down = false;
401 break;
402 case 0x53:
403 s_down = false;
404 break;
405 case 0x44:
406 d_down = false;
407 break;
411 void Engine::handleSpecialKeyDown(SomeEvent &event) {
412 switch (event.key) {
413 case 0x57:
414 w_down = true;
415 break;
416 case 0x41:
417 a_down = true;
418 break;
419 case 0x53:
420 s_down = true;
421 break;
422 case 0x44:
423 d_down = true;
424 break;
428 // handle debug keys, if they're enabled
429 caosVar v = world.variables["engine_debug_keys"];
430 if (v.hasInt() && v.getInt() == 1) {
431 if (backend->keyDown(16)) { // shift down
432 MetaRoom *n; // for pageup/pagedown
434 switch (event.key) {
435 case 45: // insert
436 world.showrooms = !world.showrooms;
437 break;
439 case 19: // pause
440 // TODO: debug pause game
441 break;
443 case 32: // space
444 // TODO: force tick
445 break;
447 case 33: // pageup
448 // TODO: previous metaroom
449 if ((world.map.getMetaRoomCount() - 1) == world.camera.getMetaRoom()->id)
450 break;
451 n = world.map.getMetaRoom(world.camera.getMetaRoom()->id + 1);
452 if (n)
453 world.camera.goToMetaRoom(n->id);
454 break;
456 case 34: // pagedown
457 // TODO: next metaroom
458 if (world.camera.getMetaRoom()->id == 0)
459 break;
460 n = world.map.getMetaRoom(world.camera.getMetaRoom()->id - 1);
461 if (n)
462 world.camera.goToMetaRoom(n->id);
463 break;
465 default: break; // to shut up warnings
470 // tell the agent with keyboard focus
471 if (world.focusagent) {
472 TextEntryPart *t = (TextEntryPart *)((CompoundAgent *)world.focusagent.get())->part(world.focuspart);
473 if (t)
474 t->handleSpecialKey(event.key);
477 // notify agents
478 caosVar k;
479 k.setInt(event.key);
480 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
481 if (!*i) continue;
482 if ((*i)->imsk_key_down)
483 (*i)->queueScript(73, 0, k); // key down script
487 static const char data_default[] = "./data";
489 static void opt_version() {
490 // We already showed the primary version bit, just throw in some random legalese
491 std::cout <<
492 "This is free software; see the source for copying conditions. There is NO" << std::endl <<
493 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." << std::endl << std::endl <<
494 "...please don't sue us." << std::endl;
497 bool Engine::parseCommandLine(int argc, char *argv[]) {
498 // variables for command-line flags
499 int optret;
500 std::vector<std::string> data_vec;
502 // generate help for backend options
503 std::string available_backends;
504 for (std::map<std::string, boost::shared_ptr<Backend> >::iterator i = possible_backends.begin(); i != possible_backends.end(); i++) {
505 if (available_backends.empty()) available_backends = i->first;
506 else available_backends += ", " + i->first;
508 available_backends = "Select the backend (options: " + available_backends + "), default is " + preferred_backend;
510 std::string available_audiobackends;
511 for (std::map<std::string, boost::shared_ptr<AudioBackend> >::iterator i = possible_audiobackends.begin(); i != possible_audiobackends.end(); i++) {
512 if (available_audiobackends.empty()) available_audiobackends = i->first;
513 else available_audiobackends += ", " + i->first;
515 available_audiobackends = "Select the audio backend (options: " + available_audiobackends + "), default is " + preferred_audiobackend;
517 // parse the command-line flags
518 po::options_description desc;
519 desc.add_options()
520 ("help,h", "Display help on command-line options")
521 ("version,V", "Display openc2e version")
522 ("silent,s", "Disable all sounds")
523 ("backend,k", po::value<std::string>(&preferred_backend)->composing(), available_backends.c_str())
524 ("audiobackend,o", po::value<std::string>(&preferred_audiobackend)->composing(), available_audiobackends.c_str())
525 ("data-path,d", po::value< std::vector<std::string> >(&data_vec)->composing(),
526 "Sets or adds a path to a data directory")
527 ("bootstrap,b", po::value< std::vector<std::string> >(&cmdline_bootstrap)->composing(),
528 "Sets or adds a path or COS file to bootstrap from")
529 ("gametype,g", po::value< std::string >(&world.gametype), "Set the game type (c1, c2, cv or c3)")
530 ("gamename,m", po::value< std::string >(&gamename), "Set the game name")
531 ("norun,n", "Don't run the game, just execute scripts")
532 ("autokill,a", "Enable autokill")
533 ("autostop", "Enable autostop (or disable it, for CV)")
535 po::variables_map vm;
536 po::store(po::parse_command_line(argc, argv, desc), vm);
537 po::notify(vm);
539 cmdline_enable_sound = !vm.count("silent");
540 cmdline_norun = vm.count("norun");
542 if (vm.count("help")) {
543 std::cout << desc << std::endl;
544 return false;
547 if (vm.count("version")) {
548 opt_version();
549 return false;
552 if (vm.count("autokill")) {
553 world.autokill = true;
556 if (vm.count("autostop")) {
557 world.autostop = true;
560 if (vm.count("data-path") == 0) {
561 std::cout << "Warning: No data path specified, trying default of '" << data_default << "', see --help if you need to specify one." << std::endl;
562 data_vec.push_back(data_default);
565 // add all the data directories to the list
566 for (std::vector<std::string>::iterator i = data_vec.begin(); i != data_vec.end(); i++) {
567 fs::path datadir(*i, fs::native);
568 if (!fs::exists(datadir)) {
569 throw creaturesException("data path '" + *i + "' doesn't exist");
571 world.data_directories.push_back(datadir);
574 // make a vague attempt at blacklisting some characters inside the gamename
575 // (it's used in directory names, registry keys, etc)
576 std::string invalidchars = "\\/:*?\"<>|";
577 for (unsigned int i = 0; i < invalidchars.size(); i++) {
578 if (gamename.find(invalidchars[i]) != gamename.npos)
579 throw creaturesException(std::string("The character ") + invalidchars[i] + " is not valid in a gamename.");
582 return true;
585 bool Engine::initialSetup() {
586 assert(world.data_directories.size() > 0);
588 // autodetect gametype if necessary
589 if (world.gametype.empty()) {
590 std::cout << "Warning: No gametype specified, ";
591 // TODO: is this sane? especially unsure about about.exe
592 if (!world.findFile("Creatures.exe").empty()) {
593 std::cout << "found Creatures.exe, assuming C1 (c1)";
594 world.gametype = "c1";
595 } else if (!world.findFile("Creatures2.exe").empty()) {
596 std::cout << "found Creatures2.exe, assuming C2 (c2)";
597 world.gametype = "c2";
598 } else if (!world.findFile("Sea-Monkeys.ico").empty()) {
599 std::cout << "found Sea-Monkeys.ico, assuming Sea-Monkeys (sm)";
600 world.gametype = "sm";
601 } else if (!world.findFile("about.exe").empty()) {
602 std::cout << "found about.exe, assuming CA, CP or CV (cv)";
603 world.gametype = "cv";
604 } else {
605 std::cout << "assuming C3/DS (c3)";
606 world.gametype = "c3";
608 std::cout << ", see --help if you need to specify one." << std::endl;
611 // set engine version
612 // TODO: set gamename
613 if (world.gametype == "c1") {
614 if (gamename.empty()) gamename = "Creatures 1";
615 version = 1;
616 } else if (world.gametype == "c2") {
617 if (gamename.empty()) gamename = "Creatures 2";
618 version = 2;
619 } else if (world.gametype == "c3") {
620 if (gamename.empty()) gamename = "Creatures 3";
621 version = 3;
622 } else if (world.gametype == "cv") {
623 if (gamename.empty()) gamename = "Creatures Village";
624 version = 3;
625 world.autostop = !world.autostop;
626 } else if (world.gametype == "sm") {
627 if (gamename.empty()) gamename = "Sea-Monkeys";
628 version = 3;
629 bmprenderer = true;
630 } else
631 throw creaturesException(boost::str(boost::format("unknown gametype '%s'!") % world.gametype));
633 // finally, add our cache directory to the end
634 world.data_directories.push_back(storageDirectory());
636 // initial setup
637 registerDelegates();
638 std::cout << "* Reading catalogue files..." << std::endl;
639 world.initCatalogue();
640 std::cout << "* Initial setup..." << std::endl;
641 world.init(); // just reads mouse cursor (we want this after the catalogue reading so we don't play "guess the filename")
642 if (engine.version > 2) {
643 std::cout << "* Reading PRAY files..." << std::endl;
644 world.praymanager.update();
647 if (cmdline_norun) preferred_backend = "null";
648 if (preferred_backend != "null") std::cout << "* Initialising backend " << preferred_backend << "..." << std::endl;
649 shared_ptr<Backend> b = possible_backends[preferred_backend];
650 if (!b) throw creaturesException("No such backend " + preferred_backend);
651 b->init(); setBackend(b);
652 possible_backends.clear();
654 if (cmdline_norun || !cmdline_enable_sound) preferred_audiobackend = "null";
655 if (preferred_audiobackend != "null") std::cout << "* Initialising audio backend " << preferred_audiobackend << "..." << std::endl;
656 shared_ptr<AudioBackend> a = possible_audiobackends[preferred_audiobackend];
657 if (!a) throw creaturesException("No such audio backend " + preferred_audiobackend);
658 try{
659 a->init(); audio = a;
660 } catch (creaturesException &e) {
661 std::cerr << "* Couldn't initialize backend " << preferred_audiobackend << ": " << e.what() << std::endl << "* Continuing without sound." << std::endl;
662 audio = shared_ptr<AudioBackend>(new NullAudioBackend());
663 audio->init();
665 possible_audiobackends.clear();
667 world.camera.setBackend(backend); // TODO: hrr
669 int listenport = backend->networkInit();
670 if (listenport != -1) {
671 // inform the user of the port used, and store it in the relevant file
672 std::cout << "Listening for connections on port " << listenport << "." << std::endl;
673 #ifndef _WIN32
674 fs::path p = fs::path(homeDirectory().native_directory_string() + "/.creaturesengine", fs::native);
675 if (!fs::exists(p))
676 fs::create_directory(p);
677 if (fs::is_directory(p)) {
678 std::ofstream f((p.native_directory_string() + "/port").c_str(), std::ios::trunc);
679 f << boost::str(boost::format("%d") % listenport);
681 #endif
684 if (world.data_directories.size() < 3) {
685 // TODO: This is a hack for DS, basically. Not sure if it works properly. - fuzzie
686 caosVar name; name.setString("engine_no_auxiliary_bootstrap_1");
687 caosVar contents; contents.setInt(1);
688 eame_variables[name] = contents;
691 // execute the initial scripts!
692 std::cout << "* Executing initial scripts..." << std::endl;
693 if (cmdline_bootstrap.size() == 0) {
694 world.executeBootstrap(false);
695 } else {
696 std::vector<std::string> scripts;
698 for (std::vector< std::string >::iterator bsi = cmdline_bootstrap.begin(); bsi != cmdline_bootstrap.end(); bsi++) {
699 fs::path scriptdir(*bsi, fs::native);
700 if (!fs::exists(scriptdir)) {
701 std::cerr << "Warning: Couldn't find a specified script directory (trying " << *bsi << ")!\n";
702 continue;
704 world.executeBootstrap(scriptdir);
708 // if there aren't any metarooms, we can't run a useful game, the user probably
709 // wanted to execute a CAOS script or something went badly wrong.
710 if (!cmdline_norun && world.map.getMetaRoomCount() == 0) {
711 shutdown();
712 throw creaturesException("No metarooms found in given bootstrap directories or files");
715 std::cout << "* Done startup." << std::endl;
717 if (cmdline_norun) {
718 // TODO: see comment above about avoiding backend when norun is set
719 std::cout << "Told not to run the world, so stopping now." << std::endl;
720 shutdown();
721 return false;
724 return true;
727 void Engine::shutdown() {
728 world.shutdown();
729 backend->shutdown();
730 audio->shutdown();
731 freeDelegates(); // does nothing if there are none (ie, no call to initialSetup)
734 fs::path Engine::homeDirectory() {
735 fs::path p;
737 #ifndef _WIN32
738 char *envhome = getenv("HOME");
739 if (envhome)
740 p = fs::path(envhome, fs::native);
741 if ((!envhome) || (!fs::is_directory(p)))
742 p = fs::path(getpwuid(getuid())->pw_dir, fs::native);
743 if (!fs::is_directory(p)) {
744 std::cerr << "Can't work out what your home directory is, giving up and using /tmp for now." << std::endl;
745 p = fs::path("/tmp", fs::native); // sigh
747 #else
748 TCHAR szPath[_MAX_PATH];
749 SHGetSpecialFolderPath(NULL, szPath, CSIDL_PERSONAL, TRUE);
751 p = fs::path(szPath, fs::native);
752 if (!fs::exists(p) || !fs::is_directory(p))
753 throw creaturesException("Windows reported that your My Documents folder is at '" + std::string(szPath) + "' but there's no directory there!");
754 #endif
756 return p;
759 fs::path Engine::storageDirectory() {
760 #ifndef _WIN32
761 std::string dirname = "/.openc2e";
762 #else
763 std::string dirname = "/My Games";
764 #endif
766 // main storage dir
767 fs::path p = fs::path(homeDirectory().native_directory_string() + dirname, fs::native);
768 if (!fs::exists(p))
769 fs::create_directory(p);
770 else if (!fs::is_directory(p))
771 throw creaturesException("Your openc2e data directory " + p.native_directory_string() + " is a file, not a directory. That's bad.");
773 // game-specific storage dir
774 p = fs::path(p.native_directory_string() + std::string("/" + gamename), fs::native);
775 if (!fs::exists(p))
776 fs::create_directory(p);
777 else if (!fs::is_directory(p))
778 throw creaturesException("Your openc2e game data directory " + p.native_directory_string() + " is a file, not a directory. That's bad.");
780 return p;
783 /* vim: set noet: */