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.
23 #include <simgear/sg_inlines.h>
24 #include <simgear/math/sg_geodesy.hxx>
25 #include <simgear/props/props_io.hxx>
26 #include <simgear/structure/exception.hxx>
27 #include <boost/mem_fn.hpp>
28 #include <boost/foreach.hpp>
30 #include <Main/globals.hxx>
32 #include <Airports/simple.hxx>
33 #include <Traffic/TrafficMgr.hxx>
35 #include "AIManager.hxx"
36 #include "AIAircraft.hxx"
38 #include "AIBallistic.hxx"
39 #include "AIStorm.hxx"
40 #include "AIThermal.hxx"
41 #include "AICarrier.hxx"
42 #include "AIStatic.hxx"
43 #include "AIMultiplayer.hxx"
44 #include "AITanker.hxx"
45 #include "AIWingman.hxx"
46 #include "AIGroundVehicle.hxx"
47 #include "AIEscort.hxx"
49 FGAIManager::FGAIManager() :
50 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
51 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
52 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
53 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
58 FGAIManager::~FGAIManager()
60 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
65 root = fgGetNode("sim/ai", true);
67 enabled = root->getNode("enabled", true);
69 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
70 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
71 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
73 user_latitude_node = fgGetNode("/position/latitude-deg", true);
74 user_longitude_node = fgGetNode("/position/longitude-deg", true);
75 user_altitude_node = fgGetNode("/position/altitude-ft", true);
76 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
77 user_heading_node = fgGetNode("/orientation/heading-deg", true);
78 user_pitch_node = fgGetNode("/orientation/pitch-deg", true);
79 user_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
80 user_roll_node = fgGetNode("/orientation/roll-deg", true);
81 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
85 FGAIManager::postinit() {
86 // postinit, so that it can access the Nasal subsystem
88 if (!root->getBoolValue("scenarios-enabled", true))
91 // scenarios enabled, AI subsystem required
92 if (!enabled->getBoolValue())
93 enabled->setBoolValue(true);
95 // process all scenarios
96 map<string, bool> scenarios;
97 for (int i = 0 ; i < root->nChildren() ; i++) {
98 SGPropertyNode *n = root->getChild(i);
99 if (strcmp(n->getName(), "scenario"))
102 string name = n->getStringValue();
106 if (scenarios.find(name) != scenarios.end()) {
107 SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
111 SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
112 processScenario(name);
113 scenarios[name] = true;
118 FGAIManager::reinit()
121 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
125 FGAIManager::bind() {
126 root = globals->get_props()->getNode("ai/models", true);
127 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
128 &FGAIManager::getNumAiObjects));
132 FGAIManager::unbind() {
133 root->untie("count");
136 void FGAIManager::removeDeadItem(FGAIBase* base)
138 FGTrafficManager *tmgr = (FGTrafficManager*) globals->get_subsystem("traffic-manager");
140 tmgr->release(base->getID());
143 SGPropertyNode *props = base->_getProps();
145 props->setBoolValue("valid", false);
148 // for backward compatibility reset properties, so that aircraft,
149 // which don't know the <valid> property, keep working
150 // TODO: remove after a while
151 props->setIntValue("id", -1);
152 props->setBoolValue("radar/in-range", false);
153 props->setIntValue("refuel/tanker", false);
157 FGAIManager::update(double dt) {
158 // initialize these for finding nearest thermals
159 range_nearest = 10000.0;
162 if (!enabled->getBoolValue())
167 // partition the list into dead followed by alive
168 ai_list_iterator firstAlive =
169 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
171 // clean up each item and finally remove from the container
172 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
176 ai_list.erase(ai_list.begin(), firstAlive);
178 // every remaining item is alive
179 BOOST_FOREACH(FGAIBase* base, ai_list) {
180 if (base->isa(FGAIBase::otThermal)) {
181 processThermal(dt, (FGAIThermal*)base);
185 } // of live AI objects iteration
187 thermal_lift_node->setDoubleValue( strength ); // for thermals
190 /** update LOD settings of all AI/MP models */
192 FGAIManager::updateLOD(SGPropertyNode* node)
195 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
199 FGAIManager::attach(FGAIBase *model)
201 const char* typeString = model->getTypeString();
202 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
206 // find free index in the property tree, if we have
207 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
208 for (i = 0; i < 10000; i++) {
209 p = root->getNode(typeString, i, false);
211 if (!p || !p->getBoolValue("valid", false))
214 if (p->getIntValue("id",-1)==model->getID()) {
215 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
219 p = root->getNode(typeString, i, true);
220 model->setManager(this, p);
221 ai_list.push_back(model);
223 model->init(model->getType()==FGAIBase::otAircraft
224 || model->getType()==FGAIBase::otMultiplayer
225 || model->getType()==FGAIBase::otStatic);
227 p->setBoolValue("valid", true);
231 FGAIManager::destroyObject( int ID ) {
232 ai_list_iterator ai_list_itr = ai_list.begin();
234 while(ai_list_itr != ai_list.end()) {
236 if ((*ai_list_itr)->getID() == ID) {
237 (*ai_list_itr)->unbind();
238 ai_list_itr = ai_list.erase(ai_list_itr);
246 FGAIManager::getNumAiObjects(void) const
248 return ai_list.size();
252 FGAIManager::fetchUserState( void ) {
254 user_latitude = user_latitude_node->getDoubleValue();
255 user_longitude = user_longitude_node->getDoubleValue();
256 user_altitude = user_altitude_node->getDoubleValue();
257 user_heading = user_heading_node->getDoubleValue();
258 user_pitch = user_pitch_node->getDoubleValue();
259 user_yaw = user_yaw_node->getDoubleValue();
260 user_speed = user_speed_node->getDoubleValue() * 0.592484;
261 user_roll = user_roll_node->getDoubleValue();
262 wind_from_east = wind_from_east_node->getDoubleValue();
263 wind_from_north = wind_from_north_node->getDoubleValue();
264 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
268 // only keep the results from the nearest thermal
270 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
273 if ( thermal->_getRange() < range_nearest ) {
274 range_nearest = thermal->_getRange();
275 strength = thermal->getStrength();
283 FGAIManager::processScenario( const string &filename ) {
285 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
290 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
295 for (int i = 0; i < scenarios->nChildren(); i++) {
296 SGPropertyNode* scEntry = scenarios->getChild(i);
298 if (strcmp(scEntry->getName(), "entry"))
300 std::string type = scEntry->getStringValue("type", "aircraft");
302 if (type == "tanker") { // refueling scenarios
303 FGAITanker* tanker = new FGAITanker;
304 tanker->readFromScenario(scEntry);
307 } else if (type == "wingman") {
308 FGAIWingman* wingman = new FGAIWingman;
309 wingman->readFromScenario(scEntry);
312 } else if (type == "aircraft") {
313 FGAIAircraft* aircraft = new FGAIAircraft;
314 aircraft->readFromScenario(scEntry);
317 } else if (type == "ship") {
318 FGAIShip* ship = new FGAIShip;
319 ship->readFromScenario(scEntry);
322 } else if (type == "carrier") {
323 FGAICarrier* carrier = new FGAICarrier;
324 carrier->readFromScenario(scEntry);
327 } else if (type == "groundvehicle") {
328 FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
329 groundvehicle->readFromScenario(scEntry);
330 attach(groundvehicle);
332 } else if (type == "escort") {
333 FGAIEscort* escort = new FGAIEscort;
334 escort->readFromScenario(scEntry);
337 } else if (type == "thunderstorm") {
338 FGAIStorm* storm = new FGAIStorm;
339 storm->readFromScenario(scEntry);
342 } else if (type == "thermal") {
343 FGAIThermal* thermal = new FGAIThermal;
344 thermal->readFromScenario(scEntry);
347 } else if (type == "ballistic") {
348 FGAIBallistic* ballistic = new FGAIBallistic;
349 ballistic->readFromScenario(scEntry);
352 } else if (type == "static") {
353 FGAIStatic* aistatic = new FGAIStatic;
354 aistatic->readFromScenario(scEntry);
363 FGAIManager::loadScenarioFile(const std::string& filename)
365 SGPath path(globals->get_fg_root());
366 path.append("AI/" + filename + ".xml");
368 SGPropertyNode_ptr root = new SGPropertyNode;
369 readProperties(path.str(), root);
371 } catch (const sg_exception &t) {
372 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
373 << path.str() << "': " << t.getFormattedMessage());
379 FGAIManager::getStartPosition(const string& id, const string& pid,
380 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
383 SGPropertyNode* root = fgGetNode("sim/ai", true);
384 if (!root->getNode("enabled", true)->getBoolValue())
387 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
388 SGPropertyNode *aiEntry = root->getChild( i );
389 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
390 string filename = aiEntry->getStringValue();
391 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
393 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
395 for (int i = 0; i < scenarios->nChildren(); i++) {
396 SGPropertyNode* scEntry = scenarios->getChild(i);
397 std::string type = scEntry->getStringValue("type");
398 std::string pnumber = scEntry->getStringValue("pennant-number");
399 std::string name = scEntry->getStringValue("name");
400 if (type == "carrier" && (pnumber == id || name == id)) {
401 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
402 carrier->readFromScenario(scEntry);
404 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
418 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
420 // we specify tgt extent (ft) according to the AIObject type
421 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
422 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
423 ai_list_iterator ai_list_itr = ai_list.begin();
424 ai_list_iterator end = ai_list.end();
426 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
427 SGVec3d cartPos(SGVec3d::fromGeod(pos));
429 while (ai_list_itr != end) {
430 double tgt_alt = (*ai_list_itr)->_getAltitude();
431 int type = (*ai_list_itr)->getType();
432 tgt_ht[type] += fuse_range;
434 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
435 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
436 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
437 // << fabs(tgt_alt - alt)
445 int id = (*ai_list_itr)->getID();
447 double range = calcRange(cartPos, (*ai_list_itr));
449 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
451 // << " type " << type
453 // << " range " << range
454 // //<< " bearing " << bearing
455 // << " alt " << tgt_alt
458 tgt_length[type] += fuse_range;
460 if (range < tgt_length[type]){
461 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
464 << " range " << range
465 << " alt " << tgt_alt
467 return (*ai_list_itr).get();
475 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
477 double distM = dist(aCartPos, aObject->getCartPos());
478 return distM * SG_METER_TO_FEET;