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_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
131 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
133 globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
134 globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
138 FGAIManager::postinit()
140 // postinit, so that it can access the Nasal subsystem
142 // scenarios enabled, AI subsystem required
143 if (!enabled->getBoolValue())
144 enabled->setBoolValue(true);
146 // process all scenarios
147 BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
148 const string& name = n->getStringValue();
152 if (_scenarios.find(name) != _scenarios.end()) {
153 SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
157 SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
163 FGAIManager::reinit()
166 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
170 FGAIManager::bind() {
171 root = globals->get_props()->getNode("ai/models", true);
172 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
173 &FGAIManager::getNumAiObjects));
177 FGAIManager::unbind() {
178 root->untie("count");
181 void FGAIManager::removeDeadItem(FGAIBase* base)
183 SGPropertyNode *props = base->_getProps();
185 props->setBoolValue("valid", false);
188 // for backward compatibility reset properties, so that aircraft,
189 // which don't know the <valid> property, keep working
190 // TODO: remove after a while
191 props->setIntValue("id", -1);
192 props->setBoolValue("radar/in-range", false);
193 props->setIntValue("refuel/tanker", false);
197 FGAIManager::update(double dt) {
198 // initialize these for finding nearest thermals
199 range_nearest = 10000.0;
202 if (!enabled->getBoolValue())
207 // partition the list into dead followed by alive
208 ai_list_iterator firstAlive =
209 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
211 // clean up each item and finally remove from the container
212 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
216 ai_list.erase(ai_list.begin(), firstAlive);
218 // every remaining item is alive
219 BOOST_FOREACH(FGAIBase* base, ai_list) {
220 if (base->isa(FGAIBase::otThermal)) {
221 processThermal(dt, (FGAIThermal*)base);
225 } // of live AI objects iteration
227 thermal_lift_node->setDoubleValue( strength ); // for thermals
230 /** update LOD settings of all AI/MP models */
232 FGAIManager::updateLOD(SGPropertyNode* node)
235 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
239 FGAIManager::attach(FGAIBase *model)
241 const char* typeString = model->getTypeString();
242 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
246 // find free index in the property tree, if we have
247 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
248 for (i = 0; i < 10000; i++) {
249 p = root->getNode(typeString, i, false);
251 if (!p || !p->getBoolValue("valid", false))
254 if (p->getIntValue("id",-1)==model->getID()) {
255 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
259 p = root->getNode(typeString, i, true);
260 model->setManager(this, p);
261 ai_list.push_back(model);
263 model->init(model->getType()==FGAIBase::otAircraft
264 || model->getType()==FGAIBase::otMultiplayer
265 || model->getType()==FGAIBase::otStatic);
267 p->setBoolValue("valid", true);
271 FGAIManager::getNumAiObjects(void) const
273 return ai_list.size();
277 FGAIManager::fetchUserState( void ) {
279 user_yaw = user_yaw_node->getDoubleValue();
280 globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
282 user_speed = user_speed_node->getDoubleValue() * 0.592484;
283 wind_from_east = wind_from_east_node->getDoubleValue();
284 wind_from_north = wind_from_north_node->getDoubleValue();
285 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
289 // only keep the results from the nearest thermal
291 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
294 if ( thermal->_getRange() < range_nearest ) {
295 range_nearest = thermal->_getRange();
296 strength = thermal->getStrength();
301 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
303 std::string name = args->getStringValue("name");
304 if (args->hasChild("load-property")) {
305 // slightly ugly, to simplify life in the dialogs, make load allow
306 // loading or unloading based on a bool property.
307 bool loadIt = fgGetBool(args->getStringValue("load-property"));
309 // user actually wants to unload, fine.
310 return unloadScenario(name);
314 if (_scenarios.find(name) != _scenarios.end()) {
315 SG_LOG(SG_AI, SG_WARN, "scenario '" << name << "' already loaded");
319 bool ok = loadScenario(name);
321 // create /sim/ai node for consistency
323 for (; root->hasChild("scenario", index); ++index) {}
325 SGPropertyNode* scenarioNode = root->getChild("scenario", index, true);
326 scenarioNode->setStringValue(name);
332 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
334 std::string name = args->getStringValue("name");
335 return unloadScenario(name);
338 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
340 addObject(definition);
344 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
346 const std::string& type = definition->getStringValue("type", "aircraft");
349 if (type == "tanker") { // refueling scenarios
351 } else if (type == "wingman") {
352 ai = new FGAIWingman;
353 } else if (type == "aircraft") {
354 ai = new FGAIAircraft;
355 } else if (type == "ship") {
357 } else if (type == "carrier") {
358 ai = new FGAICarrier;
359 } else if (type == "groundvehicle") {
360 ai = new FGAIGroundVehicle;
361 } else if (type == "escort") {
363 } else if (type == "thunderstorm") {
365 } else if (type == "thermal") {
366 ai = new FGAIThermal;
367 } else if (type == "ballistic") {
368 ai = new FGAIBallistic;
369 } else if (type == "static") {
373 ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
378 bool FGAIManager::removeObject(const SGPropertyNode* args)
380 int id = args->getIntValue("id");
381 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
382 if (ai->getID() == id) {
392 FGAIManager::loadScenario( const string &filename )
394 SGPropertyNode_ptr file = loadScenarioFile(filename);
399 SGPropertyNode_ptr scNode = file->getChild("scenario");
404 _scenarios[filename] = new Scenario(this, filename, scNode);
410 FGAIManager::unloadScenario( const string &filename)
412 ScenarioDict::iterator it = _scenarios.find(filename);
413 if (it == _scenarios.end()) {
414 SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
418 // remove /sim/ai node
419 unsigned int index = 0;
420 for (SGPropertyNode* n = NULL; (n = root->getChild("scenario", index)) != NULL; ++index) {
421 if (n->getStringValue() == filename) {
422 root->removeChild("scenario", index);
428 _scenarios.erase(it);
433 FGAIManager::loadScenarioFile(const std::string& filename)
435 SGPath path(globals->get_fg_root());
436 path.append("AI/" + filename + ".xml");
438 SGPropertyNode_ptr root = new SGPropertyNode;
439 readProperties(path.str(), root);
441 } catch (const sg_exception &t) {
442 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
443 << path.str() << "': " << t.getFormattedMessage());
449 FGAIManager::getStartPosition(const string& id, const string& pid,
450 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
453 SGPropertyNode* root = fgGetNode("sim/ai", true);
454 if (!root->getNode("enabled", true)->getBoolValue())
457 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
458 SGPropertyNode *aiEntry = root->getChild( i );
459 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
460 const string& filename = aiEntry->getStringValue();
461 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
463 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
465 for (int i = 0; i < scenarios->nChildren(); i++) {
466 SGPropertyNode* scEntry = scenarios->getChild(i);
467 const std::string& type = scEntry->getStringValue("type");
468 const std::string& pnumber = scEntry->getStringValue("pennant-number");
469 const std::string& name = scEntry->getStringValue("name");
470 if (type == "carrier" && (pnumber == id || name == id)) {
471 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
472 carrier->readFromScenario(scEntry);
474 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
488 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
490 // we specify tgt extent (ft) according to the AIObject type
491 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
492 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
493 ai_list_iterator ai_list_itr = ai_list.begin();
494 ai_list_iterator end = ai_list.end();
496 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
497 SGVec3d cartPos(SGVec3d::fromGeod(pos));
499 while (ai_list_itr != end) {
500 double tgt_alt = (*ai_list_itr)->_getAltitude();
501 int type = (*ai_list_itr)->getType();
502 tgt_ht[type] += fuse_range;
504 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
505 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
506 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
507 // << fabs(tgt_alt - alt)
515 int id = (*ai_list_itr)->getID();
517 double range = calcRangeFt(cartPos, (*ai_list_itr));
519 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
521 // << " type " << type
523 // << " range " << range
524 // //<< " bearing " << bearing
525 // << " alt " << tgt_alt
528 tgt_length[type] += fuse_range;
530 if (range < tgt_length[type]){
531 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
534 << " range " << range
535 << " alt " << tgt_alt
537 return (*ai_list_itr).get();
545 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
547 double distM = dist(aCartPos, aObject->getCartPos());
548 return distM * SG_METER_TO_FEET;