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 <boost/mem_fn.hpp>
29 #include <boost/foreach.hpp>
31 #include <Main/globals.hxx>
32 #include <Airports/airport.hxx>
34 #include "AIManager.hxx"
35 #include "AIAircraft.hxx"
37 #include "AIBallistic.hxx"
38 #include "AIStorm.hxx"
39 #include "AIThermal.hxx"
40 #include "AICarrier.hxx"
41 #include "AIStatic.hxx"
42 #include "AIMultiplayer.hxx"
43 #include "AITanker.hxx"
44 #include "AIWingman.hxx"
45 #include "AIGroundVehicle.hxx"
46 #include "AIEscort.hxx"
48 FGAIManager::FGAIManager() :
49 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
50 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
51 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
52 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
57 FGAIManager::~FGAIManager()
59 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
64 root = fgGetNode("sim/ai", true);
66 enabled = root->getNode("enabled", true);
68 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
69 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
70 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
72 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
73 user_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
74 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
78 FGAIManager::postinit() {
79 // postinit, so that it can access the Nasal subsystem
81 if (!root->getBoolValue("scenarios-enabled", true))
84 // scenarios enabled, AI subsystem required
85 if (!enabled->getBoolValue())
86 enabled->setBoolValue(true);
88 // process all scenarios
89 std::set<std::string> loadedScenarios;
90 BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
91 const string& name = n->getStringValue();
95 if (loadedScenarios.find(name) != loadedScenarios.end()) {
96 SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
100 SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
102 loadedScenarios.insert(name);
107 FGAIManager::reinit()
110 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
114 FGAIManager::bind() {
115 root = globals->get_props()->getNode("ai/models", true);
116 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
117 &FGAIManager::getNumAiObjects));
121 FGAIManager::unbind() {
122 root->untie("count");
125 void FGAIManager::removeDeadItem(FGAIBase* base)
127 SGPropertyNode *props = base->_getProps();
129 props->setBoolValue("valid", false);
132 // for backward compatibility reset properties, so that aircraft,
133 // which don't know the <valid> property, keep working
134 // TODO: remove after a while
135 props->setIntValue("id", -1);
136 props->setBoolValue("radar/in-range", false);
137 props->setIntValue("refuel/tanker", false);
141 FGAIManager::update(double dt) {
142 // initialize these for finding nearest thermals
143 range_nearest = 10000.0;
146 if (!enabled->getBoolValue())
151 // partition the list into dead followed by alive
152 ai_list_iterator firstAlive =
153 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
155 // clean up each item and finally remove from the container
156 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
160 ai_list.erase(ai_list.begin(), firstAlive);
162 // every remaining item is alive
163 BOOST_FOREACH(FGAIBase* base, ai_list) {
164 if (base->isa(FGAIBase::otThermal)) {
165 processThermal(dt, (FGAIThermal*)base);
169 } // of live AI objects iteration
171 thermal_lift_node->setDoubleValue( strength ); // for thermals
174 /** update LOD settings of all AI/MP models */
176 FGAIManager::updateLOD(SGPropertyNode* node)
179 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
183 FGAIManager::attach(FGAIBase *model)
185 const char* typeString = model->getTypeString();
186 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
190 // find free index in the property tree, if we have
191 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
192 for (i = 0; i < 10000; i++) {
193 p = root->getNode(typeString, i, false);
195 if (!p || !p->getBoolValue("valid", false))
198 if (p->getIntValue("id",-1)==model->getID()) {
199 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
203 p = root->getNode(typeString, i, true);
204 model->setManager(this, p);
205 ai_list.push_back(model);
207 model->init(model->getType()==FGAIBase::otAircraft
208 || model->getType()==FGAIBase::otMultiplayer
209 || model->getType()==FGAIBase::otStatic);
211 p->setBoolValue("valid", true);
215 FGAIManager::getNumAiObjects(void) const
217 return ai_list.size();
221 FGAIManager::fetchUserState( void ) {
223 user_yaw = user_yaw_node->getDoubleValue();
224 globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
226 user_speed = user_speed_node->getDoubleValue() * 0.592484;
227 wind_from_east = wind_from_east_node->getDoubleValue();
228 wind_from_north = wind_from_north_node->getDoubleValue();
229 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
233 // only keep the results from the nearest thermal
235 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
238 if ( thermal->_getRange() < range_nearest ) {
239 range_nearest = thermal->_getRange();
240 strength = thermal->getStrength();
248 FGAIManager::loadScenario( const string &filename ) {
250 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
255 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
260 BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
261 const std::string& type = scEntry->getStringValue("type", "aircraft");
263 if (type == "tanker") { // refueling scenarios
264 FGAITanker* tanker = new FGAITanker;
265 tanker->readFromScenario(scEntry);
268 } else if (type == "wingman") {
269 FGAIWingman* wingman = new FGAIWingman;
270 wingman->readFromScenario(scEntry);
273 } else if (type == "aircraft") {
274 FGAIAircraft* aircraft = new FGAIAircraft;
275 aircraft->readFromScenario(scEntry);
278 } else if (type == "ship") {
279 FGAIShip* ship = new FGAIShip;
280 ship->readFromScenario(scEntry);
283 } else if (type == "carrier") {
284 FGAICarrier* carrier = new FGAICarrier;
285 carrier->readFromScenario(scEntry);
288 } else if (type == "groundvehicle") {
289 FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
290 groundvehicle->readFromScenario(scEntry);
291 attach(groundvehicle);
293 } else if (type == "escort") {
294 FGAIEscort* escort = new FGAIEscort;
295 escort->readFromScenario(scEntry);
298 } else if (type == "thunderstorm") {
299 FGAIStorm* storm = new FGAIStorm;
300 storm->readFromScenario(scEntry);
303 } else if (type == "thermal") {
304 FGAIThermal* thermal = new FGAIThermal;
305 thermal->readFromScenario(scEntry);
308 } else if (type == "ballistic") {
309 FGAIBallistic* ballistic = new FGAIBallistic;
310 ballistic->readFromScenario(scEntry);
313 } else if (type == "static") {
314 FGAIStatic* aistatic = new FGAIStatic;
315 aistatic->readFromScenario(scEntry);
319 } // of scenario entry iteration
323 FGAIManager::loadScenarioFile(const std::string& filename)
325 SGPath path(globals->get_fg_root());
326 path.append("AI/" + filename + ".xml");
328 SGPropertyNode_ptr root = new SGPropertyNode;
329 readProperties(path.str(), root);
331 } catch (const sg_exception &t) {
332 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
333 << path.str() << "': " << t.getFormattedMessage());
339 FGAIManager::getStartPosition(const string& id, const string& pid,
340 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
343 SGPropertyNode* root = fgGetNode("sim/ai", true);
344 if (!root->getNode("enabled", true)->getBoolValue())
347 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
348 SGPropertyNode *aiEntry = root->getChild( i );
349 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
350 const string& filename = aiEntry->getStringValue();
351 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
353 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
355 for (int i = 0; i < scenarios->nChildren(); i++) {
356 SGPropertyNode* scEntry = scenarios->getChild(i);
357 const std::string& type = scEntry->getStringValue("type");
358 const std::string& pnumber = scEntry->getStringValue("pennant-number");
359 const std::string& name = scEntry->getStringValue("name");
360 if (type == "carrier" && (pnumber == id || name == id)) {
361 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
362 carrier->readFromScenario(scEntry);
364 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
378 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
380 // we specify tgt extent (ft) according to the AIObject type
381 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
382 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
383 ai_list_iterator ai_list_itr = ai_list.begin();
384 ai_list_iterator end = ai_list.end();
386 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
387 SGVec3d cartPos(SGVec3d::fromGeod(pos));
389 while (ai_list_itr != end) {
390 double tgt_alt = (*ai_list_itr)->_getAltitude();
391 int type = (*ai_list_itr)->getType();
392 tgt_ht[type] += fuse_range;
394 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
395 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
396 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
397 // << fabs(tgt_alt - alt)
405 int id = (*ai_list_itr)->getID();
407 double range = calcRange(cartPos, (*ai_list_itr));
409 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
411 // << " type " << type
413 // << " range " << range
414 // //<< " bearing " << bearing
415 // << " alt " << tgt_alt
418 tgt_length[type] += fuse_range;
420 if (range < tgt_length[type]){
421 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
424 << " range " << range
425 << " alt " << tgt_alt
427 return (*ai_list_itr).get();
435 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
437 double distM = dist(aCartPos, aObject->getCartPos());
438 return distM * SG_METER_TO_FEET;