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.
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
;
40 #include <sys/types.h> // passwd*
41 #include <pwd.h> // getpwuid
54 refreshdisplay
= false;
59 for (unsigned int i
= 0; i
< 10; i
++) ticktimes
[i
] = 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;
70 addPossibleBackend("null", shared_ptr
<Backend
>(new NullBackend()));
71 addPossibleAudioBackend("null", shared_ptr
<AudioBackend
>(new NullAudioBackend()));
77 void Engine::addPossibleBackend(std::string s
, boost::shared_ptr
<Backend
> b
) {
80 preferred_backend
= s
;
81 possible_backends
[s
] = b
;
84 void Engine::addPossibleAudioBackend(std::string s
, boost::shared_ptr
<AudioBackend
> b
) {
87 preferred_audiobackend
= s
;
88 possible_audiobackends
[s
] = b
;
91 void Engine::setBackend(shared_ptr
<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
);
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
);
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
120 std::istringstream
s(in
);
121 caosScript
script(world
.gametype
, "<network>"); // XXX
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
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();
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();
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
;
171 if (ticktimeptr
== 10) ticktimeptr
= 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() {
182 backend
->handleEvents();
184 // tick+draw the world, if necessary
185 bool needupdate
= needsUpdate();
191 handleKeyboardScrolling();
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"];
205 switch (v
.getInt()) {
206 case 1: // enable if CTRL is held
207 wasdMode
= backend
->keyDown(17); // CTRL
209 case 2: // enable unconditionally
210 // (this needs agent support to suppress chat bubbles etc)
217 std::cout
<< "Warning: engine_wasd_scrolling is set to unknown value " << v
.getInt() << std::endl
;
218 world
.variables
["engine_wasd_scrolling"] = caosVar(0);
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
);
238 if (!leftdown
&& !rightdown
) {
240 if (fabs(velx
) < 0.1) velx
= 0;
246 if (!updown
&& !downdown
) {
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
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() {
268 while (backend
->pollEvent(event
)) {
269 switch (event
.type
) {
270 case eventresizewindow
:
271 handleResizedWindow(event
);
275 handleMouseMove(event
);
278 case eventmousebuttonup
:
279 case eventmousebuttondown
:
280 handleMouseButton(event
);
284 handleKeyDown(event
);
287 case eventspecialkeydown
:
288 handleSpecialKeyDown(event
);
291 case eventspecialkeyup
:
292 handleSpecialKeyUp(event
);
305 void Engine::handleResizedWindow(SomeEvent
&event
) {
307 for (std::list
<boost::shared_ptr
<Agent
> >::iterator i
= world
.agents
.begin(); i
!= world
.agents
.end(); i
++) {
309 (*i
)->queueScript(123, 0); // window resized script
313 void Engine::handleMouseMove(SomeEvent
&event
) {
315 world
.hand()->handleEvent(event
);
318 for (std::list
<boost::shared_ptr
<Agent
> >::iterator i
= world
.agents
.begin(); i
!= world
.agents
.end(); i
++) {
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
) {
330 for (std::list
<boost::shared_ptr
<Agent
> >::iterator i
= world
.agents
.begin(); i
!= world
.agents
.end(); i
++) {
332 if ((event
.type
== eventmousebuttonup
&& (*i
)->imsk_mouse_up
) ||
333 (event
.type
== eventmousebuttondown
&& (*i
)->imsk_mouse_down
)) {
334 // set the button value as necessary
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;
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
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
358 if (event
.button
== buttonwheeldown
)
362 (*i
)->queueScript(78, 0, delta
); // Raw Mouse Wheel
366 world
.hand()->handleEvent(event
);
369 void Engine::handleKeyDown(SomeEvent
&event
) {
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
);
381 t
->handleKey(event
.key
);
387 for (std::list
<boost::shared_ptr
<Agent
> >::iterator i
= world
.agents
.begin(); i
!= world
.agents
.end(); i
++) {
389 if ((*i
)->imsk_translated_char
)
390 (*i
)->queueScript(79, 0, k
); // translated char script
394 void Engine::handleSpecialKeyUp(SomeEvent
&event
) {
411 void Engine::handleSpecialKeyDown(SomeEvent
&event
) {
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
436 world
.showrooms
= !world
.showrooms
;
440 // TODO: debug pause game
448 // TODO: previous metaroom
449 if ((world
.map
.getMetaRoomCount() - 1) == world
.camera
.getMetaRoom()->id
)
451 n
= world
.map
.getMetaRoom(world
.camera
.getMetaRoom()->id
+ 1);
453 world
.camera
.goToMetaRoom(n
->id
);
457 // TODO: next metaroom
458 if (world
.camera
.getMetaRoom()->id
== 0)
460 n
= world
.map
.getMetaRoom(world
.camera
.getMetaRoom()->id
- 1);
462 world
.camera
.goToMetaRoom(n
->id
);
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
);
474 t
->handleSpecialKey(event
.key
);
480 for (std::list
<boost::shared_ptr
<Agent
> >::iterator i
= world
.agents
.begin(); i
!= world
.agents
.end(); i
++) {
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
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
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
;
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
);
539 cmdline_enable_sound
= !vm
.count("silent");
540 cmdline_norun
= vm
.count("norun");
542 if (vm
.count("help")) {
543 std::cout
<< desc
<< std::endl
;
547 if (vm
.count("version")) {
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.");
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";
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";
616 } else if (world
.gametype
== "c2") {
617 if (gamename
.empty()) gamename
= "Creatures 2";
619 } else if (world
.gametype
== "c3") {
620 if (gamename
.empty()) gamename
= "Creatures 3";
622 } else if (world
.gametype
== "cv") {
623 if (gamename
.empty()) gamename
= "Creatures Village";
625 world
.autostop
= !world
.autostop
;
626 } else if (world
.gametype
== "sm") {
627 if (gamename
.empty()) gamename
= "Sea-Monkeys";
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());
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
);
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());
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
;
674 fs::path p
= fs::path(homeDirectory().native_directory_string() + "/.creaturesengine", fs::native
);
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
);
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);
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";
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) {
712 throw creaturesException("No metarooms found in given bootstrap directories or files");
715 std::cout
<< "* Done startup." << std::endl
;
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
;
727 void Engine::shutdown() {
731 freeDelegates(); // does nothing if there are none (ie, no call to initialSetup)
734 fs::path
Engine::homeDirectory() {
738 char *envhome
= getenv("HOME");
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
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!");
759 fs::path
Engine::storageDirectory() {
761 std::string dirname
= "/.openc2e";
763 std::string dirname
= "/My Games";
767 fs::path p
= fs::path(homeDirectory().native_directory_string() + dirname
, fs::native
);
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
);
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.");