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");
88 std::string moduleName = "scenario_" + _internalName;
89 if (!_unloadScript.empty()) {
90 nasalSys->createModule(moduleName.c_str(), moduleName.c_str(),
91 _unloadScript.c_str(), _unloadScript.size(),
95 nasalSys->deleteModule(moduleName.c_str());
98 std::vector<FGAIBasePtr> _objects;
99 std::string _internalName;
100 std::string _unloadScript;
103 ///////////////////////////////////////////////////////////////////////////////
105 FGAIManager::FGAIManager() :
106 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
107 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
108 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
109 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
114 FGAIManager::~FGAIManager()
116 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
120 FGAIManager::init() {
121 root = fgGetNode("sim/ai", true);
123 enabled = root->getNode("enabled", true);
125 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
126 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
127 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
129 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
130 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
132 globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
133 globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
137 FGAIManager::postinit()
139 // postinit, so that it can access the Nasal subsystem
141 // scenarios enabled, AI subsystem required
142 if (!enabled->getBoolValue())
143 enabled->setBoolValue(true);
145 // process all scenarios
146 BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
147 const string& name = n->getStringValue();
151 if (_scenarios.find(name) != _scenarios.end()) {
152 SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
156 SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
162 FGAIManager::reinit()
164 // shutdown scenarios
165 unloadAllScenarios();
168 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
170 // (re-)load scenarios
175 FGAIManager::shutdown()
177 unloadAllScenarios();
181 FGAIManager::bind() {
182 root = globals->get_props()->getNode("ai/models", true);
183 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
184 &FGAIManager::getNumAiObjects));
188 FGAIManager::unbind() {
189 root->untie("count");
192 void FGAIManager::removeDeadItem(FGAIBase* base)
194 SGPropertyNode *props = base->_getProps();
196 props->setBoolValue("valid", false);
199 // for backward compatibility reset properties, so that aircraft,
200 // which don't know the <valid> property, keep working
201 // TODO: remove after a while
202 props->setIntValue("id", -1);
203 props->setBoolValue("radar/in-range", false);
204 props->setIntValue("refuel/tanker", false);
208 FGAIManager::update(double dt) {
209 // initialize these for finding nearest thermals
210 range_nearest = 10000.0;
213 if (!enabled->getBoolValue())
218 // partition the list into dead followed by alive
219 ai_list_iterator firstAlive =
220 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
222 // clean up each item and finally remove from the container
223 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
227 ai_list.erase(ai_list.begin(), firstAlive);
229 // every remaining item is alive. update them in turn, but guard for
230 // exceptions, so a single misbehaving AI object doesn't bring down the
232 BOOST_FOREACH(FGAIBase* base, ai_list) {
234 if (base->isa(FGAIBase::otThermal)) {
235 processThermal(dt, (FGAIThermal*)base);
239 } catch (sg_exception& e) {
240 SG_LOG(SG_AI, SG_WARN, "caught exception updating AI model:" << base->_getName()<< ", which will be killed."
241 "\n\tError:" << e.getFormattedMessage());
244 } // of live AI objects iteration
246 thermal_lift_node->setDoubleValue( strength ); // for thermals
249 /** update LOD settings of all AI/MP models */
251 FGAIManager::updateLOD(SGPropertyNode* node)
254 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
258 FGAIManager::attach(FGAIBase *model)
260 const char* typeString = model->getTypeString();
261 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
265 // find free index in the property tree, if we have
266 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
267 for (i = 0; i < 10000; i++) {
268 p = root->getNode(typeString, i, false);
270 if (!p || !p->getBoolValue("valid", false))
273 if (p->getIntValue("id",-1)==model->getID()) {
274 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
278 p = root->getNode(typeString, i, true);
279 model->setManager(this, p);
280 ai_list.push_back(model);
282 model->init(model->getType()==FGAIBase::otAircraft
283 || model->getType()==FGAIBase::otMultiplayer
284 || model->getType()==FGAIBase::otStatic);
286 p->setBoolValue("valid", true);
290 FGAIManager::getNumAiObjects() const
292 return ai_list.size();
296 FGAIManager::fetchUserState( void ) {
298 globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
299 user_speed = user_speed_node->getDoubleValue() * 0.592484;
300 wind_from_east = wind_from_east_node->getDoubleValue();
301 wind_from_north = wind_from_north_node->getDoubleValue();
302 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
306 // only keep the results from the nearest thermal
308 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
311 if ( thermal->_getRange() < range_nearest ) {
312 range_nearest = thermal->_getRange();
313 strength = thermal->getStrength();
318 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
320 std::string name = args->getStringValue("name");
321 if (args->hasChild("load-property")) {
322 // slightly ugly, to simplify life in the dialogs, make load allow
323 // loading or unloading based on a bool property.
324 bool loadIt = fgGetBool(args->getStringValue("load-property"));
326 // user actually wants to unload, fine.
327 return unloadScenario(name);
331 if (_scenarios.find(name) != _scenarios.end()) {
332 SG_LOG(SG_AI, SG_WARN, "scenario '" << name << "' already loaded");
336 bool ok = loadScenario(name);
338 // create /sim/ai node for consistency
340 for (; root->hasChild("scenario", index); ++index) {}
342 SGPropertyNode* scenarioNode = root->getChild("scenario", index, true);
343 scenarioNode->setStringValue(name);
349 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
351 std::string name = args->getStringValue("name");
352 return unloadScenario(name);
355 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
357 addObject(definition);
361 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
363 const std::string& type = definition->getStringValue("type", "aircraft");
366 if (type == "tanker") { // refueling scenarios
368 } else if (type == "wingman") {
369 ai = new FGAIWingman;
370 } else if (type == "aircraft") {
371 ai = new FGAIAircraft;
372 } else if (type == "ship") {
374 } else if (type == "carrier") {
375 ai = new FGAICarrier;
376 } else if (type == "groundvehicle") {
377 ai = new FGAIGroundVehicle;
378 } else if (type == "escort") {
380 } else if (type == "thunderstorm") {
382 } else if (type == "thermal") {
383 ai = new FGAIThermal;
384 } else if (type == "ballistic") {
385 ai = new FGAIBallistic;
386 } else if (type == "static") {
390 ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
395 bool FGAIManager::removeObject(const SGPropertyNode* args)
397 int id = args->getIntValue("id");
398 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
399 if (ai->getID() == id) {
408 FGAIBasePtr FGAIManager::getObjectFromProperty(const SGPropertyNode* aProp) const
410 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
411 if (ai->_getProps() == aProp) {
414 } // of AI objects iteration
420 FGAIManager::loadScenario( const string &filename )
422 SGPropertyNode_ptr file = loadScenarioFile(filename);
427 SGPropertyNode_ptr scNode = file->getChild("scenario");
432 _scenarios[filename] = new Scenario(this, filename, scNode);
438 FGAIManager::unloadScenario( const string &filename)
440 ScenarioDict::iterator it = _scenarios.find(filename);
441 if (it == _scenarios.end()) {
442 SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
446 // remove /sim/ai node
447 unsigned int index = 0;
448 for (SGPropertyNode* n = NULL; (n = root->getChild("scenario", index)) != NULL; ++index) {
449 if (n->getStringValue() == filename) {
450 root->removeChild("scenario", index);
456 _scenarios.erase(it);
461 FGAIManager::unloadAllScenarios()
463 ScenarioDict::iterator it = _scenarios.begin();
464 for (; it != _scenarios.end(); ++it) {
466 } // of scenarios iteration
469 // remove /sim/ai node
470 root->removeChildren("scenario");
476 FGAIManager::loadScenarioFile(const std::string& filename)
478 SGPath path(globals->get_fg_root());
479 path.append("AI/" + filename + ".xml");
481 SGPropertyNode_ptr root = new SGPropertyNode;
482 readProperties(path.str(), root);
484 } catch (const sg_exception &t) {
485 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
486 << path.str() << "': " << t.getFormattedMessage());
492 FGAIManager::getStartPosition(const string& id, const string& pid,
493 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
496 SGPropertyNode* root = fgGetNode("sim/ai", true);
497 if (!root->getNode("enabled", true)->getBoolValue())
500 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
501 SGPropertyNode *aiEntry = root->getChild( i );
502 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
503 const string& filename = aiEntry->getStringValue();
504 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
506 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
508 for (int i = 0; i < scenarios->nChildren(); i++) {
509 SGPropertyNode* scEntry = scenarios->getChild(i);
510 const std::string& type = scEntry->getStringValue("type");
511 const std::string& pnumber = scEntry->getStringValue("pennant-number");
512 const std::string& name = scEntry->getStringValue("name");
513 if (type == "carrier" && (pnumber == id || name == id)) {
514 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
515 carrier->readFromScenario(scEntry);
517 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
531 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
533 // we specify tgt extent (ft) according to the AIObject type
534 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
535 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
536 ai_list_iterator ai_list_itr = ai_list.begin();
537 ai_list_iterator end = ai_list.end();
539 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
540 SGVec3d cartPos(SGVec3d::fromGeod(pos));
542 while (ai_list_itr != end) {
543 double tgt_alt = (*ai_list_itr)->_getAltitude();
544 int type = (*ai_list_itr)->getType();
545 tgt_ht[type] += fuse_range;
547 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
548 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
549 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
550 // << fabs(tgt_alt - alt)
558 int id = (*ai_list_itr)->getID();
560 double range = calcRangeFt(cartPos, (*ai_list_itr));
562 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
564 // << " type " << type
566 // << " range " << range
567 // //<< " bearing " << bearing
568 // << " alt " << tgt_alt
571 tgt_length[type] += fuse_range;
573 if (range < tgt_length[type]){
574 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
577 << " range " << range
578 << " alt " << tgt_alt
580 return (*ai_list_itr).get();
588 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
590 double distM = dist(aCartPos, aObject->getCartPos());
591 return distM * SG_METER_TO_FEET;