1 // AIManager.cxx Based on David Luff's AIMgr:
2 // - a global management type for AI objects
4 // Written by David Culp, started October 2003.
5 // - davidculp2@comcast.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 #include <simgear/sg_inlines.h>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/structure/commands.hxx>
29 #include <simgear/structure/SGBinding.hxx>
31 #include <boost/mem_fn.hpp>
32 #include <boost/foreach.hpp>
34 #include <Main/globals.hxx>
35 #include <Airports/airport.hxx>
36 #include <Scripting/NasalSys.hxx>
38 #include "AIManager.hxx"
39 #include "AIAircraft.hxx"
41 #include "AIBallistic.hxx"
42 #include "AIStorm.hxx"
43 #include "AIThermal.hxx"
44 #include "AICarrier.hxx"
45 #include "AIStatic.hxx"
46 #include "AIMultiplayer.hxx"
47 #include "AITanker.hxx"
48 #include "AIWingman.hxx"
49 #include "AIGroundVehicle.hxx"
50 #include "AIEscort.hxx"
52 class FGAIManager::Scenario
55 Scenario(FGAIManager* man, const std::string& nm, SGPropertyNode* scenarios) :
58 BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
59 FGAIBasePtr ai = man->addObject(scEntry);
61 _objects.push_back(ai);
63 } // of scenario entry iteration
65 SGPropertyNode* nasalScripts = scenarios->getChild("nasal");
70 _unloadScript = nasalScripts->getStringValue("unload");
71 std::string loadScript = nasalScripts->getStringValue("load");
72 if (!loadScript.empty()) {
73 FGNasalSys* nasalSys = (FGNasalSys*) globals->get_subsystem("nasal");
74 std::string moduleName = "scenario_" + _internalName;
75 nasalSys->createModule(moduleName.c_str(), moduleName.c_str(),
76 loadScript.c_str(), loadScript.size(),
83 BOOST_FOREACH(FGAIBasePtr ai, _objects) {
87 FGNasalSys* nasalSys = (FGNasalSys*) globals->get_subsystem("nasal");
91 std::string moduleName = "scenario_" + _internalName;
92 if (!_unloadScript.empty()) {
93 nasalSys->createModule(moduleName.c_str(), moduleName.c_str(),
94 _unloadScript.c_str(), _unloadScript.size(),
98 nasalSys->deleteModule(moduleName.c_str());
101 std::vector<FGAIBasePtr> _objects;
102 std::string _internalName;
103 std::string _unloadScript;
106 ///////////////////////////////////////////////////////////////////////////////
108 FGAIManager::FGAIManager() :
109 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
110 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
111 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
112 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
117 FGAIManager::~FGAIManager()
119 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
123 FGAIManager::init() {
124 root = fgGetNode("sim/ai", true);
126 enabled = root->getNode("enabled", true);
128 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
129 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
130 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
132 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
133 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
135 globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
136 globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
137 _environmentVisiblity = fgGetNode("/environment/visibility-m");
141 FGAIManager::postinit()
143 // postinit, so that it can access the Nasal subsystem
145 // scenarios enabled, AI subsystem required
146 if (!enabled->getBoolValue())
147 enabled->setBoolValue(true);
149 // process all scenarios
150 BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
151 const string& name = n->getStringValue();
155 if (_scenarios.find(name) != _scenarios.end()) {
156 SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
160 SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
166 FGAIManager::reinit()
168 // shutdown scenarios
169 unloadAllScenarios();
172 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
174 // (re-)load scenarios
179 FGAIManager::shutdown()
181 unloadAllScenarios();
183 BOOST_FOREACH(FGAIBase* ai, ai_list) {
188 _environmentVisiblity.clear();
190 globals->get_commands()->removeCommand("load-scenario");
191 globals->get_commands()->removeCommand("unload-scenario");
195 FGAIManager::bind() {
196 root = globals->get_props()->getNode("ai/models", true);
197 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
198 &FGAIManager::getNumAiObjects));
202 FGAIManager::unbind() {
203 root->untie("count");
206 void FGAIManager::removeDeadItem(FGAIBase* base)
208 SGPropertyNode *props = base->_getProps();
210 props->setBoolValue("valid", false);
213 // for backward compatibility reset properties, so that aircraft,
214 // which don't know the <valid> property, keep working
215 // TODO: remove after a while
216 props->setIntValue("id", -1);
217 props->setBoolValue("radar/in-range", false);
218 props->setIntValue("refuel/tanker", false);
222 FGAIManager::update(double dt) {
223 // initialize these for finding nearest thermals
224 range_nearest = 10000.0;
227 if (!enabled->getBoolValue())
232 // partition the list into dead followed by alive
233 ai_list_iterator firstAlive =
234 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
236 // clean up each item and finally remove from the container
237 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
241 ai_list.erase(ai_list.begin(), firstAlive);
243 // every remaining item is alive. update them in turn, but guard for
244 // exceptions, so a single misbehaving AI object doesn't bring down the
246 BOOST_FOREACH(FGAIBase* base, ai_list) {
248 if (base->isa(FGAIBase::otThermal)) {
249 processThermal(dt, (FGAIThermal*)base);
253 } catch (sg_exception& e) {
254 SG_LOG(SG_AI, SG_WARN, "caught exception updating AI model:" << base->_getName()<< ", which will be killed."
255 "\n\tError:" << e.getFormattedMessage());
258 } // of live AI objects iteration
260 thermal_lift_node->setDoubleValue( strength ); // for thermals
263 /** update LOD settings of all AI/MP models */
265 FGAIManager::updateLOD(SGPropertyNode* node)
268 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
272 FGAIManager::attach(FGAIBase *model)
274 const char* typeString = model->getTypeString();
275 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
279 // find free index in the property tree, if we have
280 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
281 for (i = 0; i < 10000; i++) {
282 p = root->getNode(typeString, i, false);
284 if (!p || !p->getBoolValue("valid", false))
287 if (p->getIntValue("id",-1)==model->getID()) {
288 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
292 p = root->getNode(typeString, i, true);
293 model->setManager(this, p);
294 ai_list.push_back(model);
296 model->init(model->getType()==FGAIBase::otAircraft
297 || model->getType()==FGAIBase::otMultiplayer
298 || model->getType()==FGAIBase::otStatic);
300 p->setBoolValue("valid", true);
303 bool FGAIManager::isVisible(const SGGeod& pos) const
305 double visibility_meters = _environmentVisiblity->getDoubleValue();
306 return ( dist(globals->get_view_position_cart(), SGVec3d::fromGeod(pos)) ) <= visibility_meters;
310 FGAIManager::getNumAiObjects() const
312 return ai_list.size();
316 FGAIManager::fetchUserState( void ) {
318 globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
319 user_speed = user_speed_node->getDoubleValue() * 0.592484;
320 wind_from_east = wind_from_east_node->getDoubleValue();
321 wind_from_north = wind_from_north_node->getDoubleValue();
322 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
326 // only keep the results from the nearest thermal
328 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
331 if ( thermal->_getRange() < range_nearest ) {
332 range_nearest = thermal->_getRange();
333 strength = thermal->getStrength();
338 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
340 std::string name = args->getStringValue("name");
341 if (args->hasChild("load-property")) {
342 // slightly ugly, to simplify life in the dialogs, make load allow
343 // loading or unloading based on a bool property.
344 bool loadIt = fgGetBool(args->getStringValue("load-property"));
346 // user actually wants to unload, fine.
347 return unloadScenario(name);
351 if (_scenarios.find(name) != _scenarios.end()) {
352 SG_LOG(SG_AI, SG_WARN, "scenario '" << name << "' already loaded");
356 bool ok = loadScenario(name);
358 // create /sim/ai node for consistency
360 for (; root->hasChild("scenario", index); ++index) {}
362 SGPropertyNode* scenarioNode = root->getChild("scenario", index, true);
363 scenarioNode->setStringValue(name);
369 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
371 std::string name = args->getStringValue("name");
372 return unloadScenario(name);
375 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
377 addObject(definition);
381 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
383 const std::string& type = definition->getStringValue("type", "aircraft");
386 if (type == "tanker") { // refueling scenarios
388 } else if (type == "wingman") {
389 ai = new FGAIWingman;
390 } else if (type == "aircraft") {
391 ai = new FGAIAircraft;
392 } else if (type == "ship") {
394 } else if (type == "carrier") {
395 ai = new FGAICarrier;
396 } else if (type == "groundvehicle") {
397 ai = new FGAIGroundVehicle;
398 } else if (type == "escort") {
400 } else if (type == "thunderstorm") {
402 } else if (type == "thermal") {
403 ai = new FGAIThermal;
404 } else if (type == "ballistic") {
405 ai = new FGAIBallistic;
406 } else if (type == "static") {
410 ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
413 SG_LOG(SG_AI, SG_DEBUG, "attached scenario " << ai->_getName());
417 SG_LOG(SG_AI, SG_ALERT, "killed invalid scenario " << ai->_getName());
422 bool FGAIManager::removeObject(const SGPropertyNode* args)
424 int id = args->getIntValue("id");
425 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
426 if (ai->getID() == id) {
435 FGAIBasePtr FGAIManager::getObjectFromProperty(const SGPropertyNode* aProp) const
437 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
438 if (ai->_getProps() == aProp) {
441 } // of AI objects iteration
447 FGAIManager::loadScenario( const string &filename )
449 SGPropertyNode_ptr file = loadScenarioFile(filename);
454 SGPropertyNode_ptr scNode = file->getChild("scenario");
459 _scenarios[filename] = new Scenario(this, filename, scNode);
465 FGAIManager::unloadScenario( const string &filename)
467 ScenarioDict::iterator it = _scenarios.find(filename);
468 if (it == _scenarios.end()) {
469 SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
473 // remove /sim/ai node
474 unsigned int index = 0;
475 for (SGPropertyNode* n = NULL; (n = root->getChild("scenario", index)) != NULL; ++index) {
476 if (n->getStringValue() == filename) {
477 root->removeChild("scenario", index);
483 _scenarios.erase(it);
488 FGAIManager::unloadAllScenarios()
490 ScenarioDict::iterator it = _scenarios.begin();
491 for (; it != _scenarios.end(); ++it) {
493 } // of scenarios iteration
496 // remove /sim/ai node
497 root->removeChildren("scenario");
503 FGAIManager::loadScenarioFile(const std::string& filename)
505 SGPath path(globals->get_fg_root());
506 path.append("AI/" + filename + ".xml");
508 SGPropertyNode_ptr root = new SGPropertyNode;
509 readProperties(path.str(), root);
511 } catch (const sg_exception &t) {
512 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
513 << path.str() << "': " << t.getFormattedMessage());
519 FGAIManager::getStartPosition(const string& id, const string& pid,
520 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
523 SGPropertyNode* root = fgGetNode("sim/ai", true);
524 if (!root->getNode("enabled", true)->getBoolValue())
527 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
528 SGPropertyNode *aiEntry = root->getChild( i );
529 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
530 const string& filename = aiEntry->getStringValue();
531 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
533 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
535 for (int i = 0; i < scenarios->nChildren(); i++) {
536 SGPropertyNode* scEntry = scenarios->getChild(i);
537 const std::string& type = scEntry->getStringValue("type");
538 const std::string& pnumber = scEntry->getStringValue("pennant-number");
539 const std::string& name = scEntry->getStringValue("name");
540 if (type == "carrier" && (pnumber == id || name == id)) {
541 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
542 carrier->readFromScenario(scEntry);
544 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
558 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
560 // we specify tgt extent (ft) according to the AIObject type
561 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
562 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
563 ai_list_iterator ai_list_itr = ai_list.begin();
564 ai_list_iterator end = ai_list.end();
566 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
567 SGVec3d cartPos(SGVec3d::fromGeod(pos));
569 while (ai_list_itr != end) {
570 double tgt_alt = (*ai_list_itr)->_getAltitude();
571 int type = (*ai_list_itr)->getType();
572 tgt_ht[type] += fuse_range;
574 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
575 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
576 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
577 // << fabs(tgt_alt - alt)
585 int id = (*ai_list_itr)->getID();
587 double range = calcRangeFt(cartPos, (*ai_list_itr));
589 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
591 // << " type " << type
593 // << " range " << range
594 // //<< " bearing " << bearing
595 // << " alt " << tgt_alt
598 tgt_length[type] += fuse_range;
600 if (range < tgt_length[type]){
601 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
604 << " range " << range
605 << " alt " << tgt_alt
607 return (*ai_list_itr).get();
615 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
617 double distM = dist(aCartPos, aObject->getCartPos());
618 return distM * SG_METER_TO_FEET;