]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
Bug 1153, guard against no current waypoint.
[flightgear.git] / src / AIModel / AIManager.cxx
1 // AIManager.cxx  Based on David Luff's AIMgr:
2 // - a global management type for AI objects
3 //
4 // Written by David Culp, started October 2003.
5 // - davidculp2@comcast.net 
6 //
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.
11 //
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.
16 //
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.
20
21 #include <cstring>
22 #include <algorithm>
23
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>
30
31 #include <boost/mem_fn.hpp>
32 #include <boost/foreach.hpp>
33
34 #include <Main/globals.hxx>
35 #include <Airports/airport.hxx>
36 #include <Scripting/NasalSys.hxx>
37
38 #include "AIManager.hxx"
39 #include "AIAircraft.hxx"
40 #include "AIShip.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"
51
52 class FGAIManager::Scenario
53 {
54 public:
55     Scenario(FGAIManager* man, const std::string& nm, SGPropertyNode* scenarios) :
56         _internalName(nm)
57     {
58         BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
59             FGAIBasePtr ai = man->addObject(scEntry);
60             if (ai) {
61                 _objects.push_back(ai);
62             }
63         } // of scenario entry iteration
64         
65         SGPropertyNode* nasalScripts = scenarios->getChild("nasal");
66         if (!nasalScripts) {
67             return;
68         }
69         
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(),
77                                    0);
78         }
79     }
80     
81     ~Scenario()
82     {
83         BOOST_FOREACH(FGAIBasePtr ai, _objects) {
84             ai->setDie(true);
85         }
86         
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(),
92                                    0);
93         }
94         
95         nasalSys->deleteModule(moduleName.c_str());
96     }
97 private:
98     std::vector<FGAIBasePtr> _objects;
99     std::string _internalName;
100     std::string _unloadScript;
101 };
102
103 ///////////////////////////////////////////////////////////////////////////////
104
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)))
110 {
111
112 }
113
114 FGAIManager::~FGAIManager()
115 {
116     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
117 }
118
119 void
120 FGAIManager::init() {
121     root = fgGetNode("sim/ai", true);
122
123     enabled = root->getNode("enabled", true);
124
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);
128
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);
132     
133     globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
134     globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
135 }
136
137 void
138 FGAIManager::postinit()
139 {
140     // postinit, so that it can access the Nasal subsystem
141
142     // scenarios enabled, AI subsystem required
143     if (!enabled->getBoolValue())
144         enabled->setBoolValue(true);
145
146     // process all scenarios
147     BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
148         const string& name = n->getStringValue();
149         if (name.empty())
150             continue;
151
152         if (_scenarios.find(name) != _scenarios.end()) {
153             SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
154             continue;
155         }
156
157         SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
158         loadScenario(name);
159     }
160 }
161
162 void
163 FGAIManager::reinit()
164 {
165     // shutdown scenarios
166     unloadAllScenarios();
167     
168     update(0.0);
169     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
170     
171     // (re-)load scenarios
172     postinit();
173 }
174
175 void
176 FGAIManager::shutdown()
177 {
178     unloadAllScenarios();
179 }
180
181 void
182 FGAIManager::bind() {
183     root = globals->get_props()->getNode("ai/models", true);
184     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
185         &FGAIManager::getNumAiObjects));
186 }
187
188 void
189 FGAIManager::unbind() {
190     root->untie("count");
191 }
192
193 void FGAIManager::removeDeadItem(FGAIBase* base)
194 {
195     SGPropertyNode *props = base->_getProps();
196     
197     props->setBoolValue("valid", false);
198     base->unbind();
199     
200     // for backward compatibility reset properties, so that aircraft,
201     // which don't know the <valid> property, keep working
202     // TODO: remove after a while
203     props->setIntValue("id", -1);
204     props->setBoolValue("radar/in-range", false);
205     props->setIntValue("refuel/tanker", false);
206 }
207
208 void
209 FGAIManager::update(double dt) {
210     // initialize these for finding nearest thermals
211     range_nearest = 10000.0;
212     strength = 0.0;
213
214     if (!enabled->getBoolValue())
215         return;
216
217     fetchUserState();
218
219     // partition the list into dead followed by alive
220     ai_list_iterator firstAlive =
221       std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
222     
223     // clean up each item and finally remove from the container
224     for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
225         removeDeadItem(*it);
226     }
227   
228     ai_list.erase(ai_list.begin(), firstAlive);
229   
230     // every remaining item is alive. update them in turn, but guard for
231     // exceptions, so a single misbehaving AI object doesn't bring down the
232     // entire subsystem.
233     BOOST_FOREACH(FGAIBase* base, ai_list) {
234         try {
235             if (base->isa(FGAIBase::otThermal)) {
236                 processThermal(dt, (FGAIThermal*)base);
237             } else {
238                 base->update(dt);
239             }
240         } catch (sg_exception& e) {
241             SG_LOG(SG_AI, SG_WARN, "caught exception updating AI model:" << base->_getName()<< ", which will be killed."
242                    "\n\tError:" << e.getFormattedMessage());
243             base->setDie(true);
244         }
245     } // of live AI objects iteration
246
247     thermal_lift_node->setDoubleValue( strength );  // for thermals
248 }
249
250 /** update LOD settings of all AI/MP models */
251 void
252 FGAIManager::updateLOD(SGPropertyNode* node)
253 {
254     SG_UNUSED(node);
255     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
256 }
257
258 void
259 FGAIManager::attach(FGAIBase *model)
260 {
261     const char* typeString = model->getTypeString();
262     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
263     SGPropertyNode* p;
264     int i;
265
266     // find free index in the property tree, if we have
267     // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
268     for (i = 0; i < 10000; i++) {
269         p = root->getNode(typeString, i, false);
270
271         if (!p || !p->getBoolValue("valid", false))
272             break;
273
274         if (p->getIntValue("id",-1)==model->getID()) {
275             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
276         }
277     }
278
279     p = root->getNode(typeString, i, true);
280     model->setManager(this, p);
281     ai_list.push_back(model);
282
283     model->init(model->getType()==FGAIBase::otAircraft
284         || model->getType()==FGAIBase::otMultiplayer
285         || model->getType()==FGAIBase::otStatic);
286     model->bind();
287     p->setBoolValue("valid", true);
288 }
289
290 int
291 FGAIManager::getNumAiObjects(void) const
292 {
293     return ai_list.size();
294 }
295
296 void
297 FGAIManager::fetchUserState( void ) {
298
299     user_yaw       = user_yaw_node->getDoubleValue();
300     globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
301
302     user_speed     = user_speed_node->getDoubleValue() * 0.592484;
303     wind_from_east = wind_from_east_node->getDoubleValue();
304     wind_from_north   = wind_from_north_node->getDoubleValue();
305     user_altitude_agl = user_altitude_agl_node->getDoubleValue();
306
307 }
308
309 // only keep the results from the nearest thermal
310 void
311 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
312     thermal->update(dt);
313
314     if ( thermal->_getRange() < range_nearest ) {
315         range_nearest = thermal->_getRange();
316         strength = thermal->getStrength();
317     }
318
319 }
320
321 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
322 {
323     std::string name = args->getStringValue("name");
324     if (args->hasChild("load-property")) {
325         // slightly ugly, to simplify life in the dialogs, make load allow
326         // loading or unloading based on a bool property.
327         bool loadIt = fgGetBool(args->getStringValue("load-property"));
328         if (!loadIt) {
329             // user actually wants to unload, fine.
330             return unloadScenario(name);
331         }
332     }
333     
334     if (_scenarios.find(name) != _scenarios.end()) {
335         SG_LOG(SG_AI, SG_WARN, "scenario '" << name << "' already loaded");
336         return false;
337     }
338     
339     bool ok = loadScenario(name);
340     if (ok) {
341         // create /sim/ai node for consistency
342         int index = 0;
343         for (; root->hasChild("scenario", index); ++index) {}
344         
345         SGPropertyNode* scenarioNode = root->getChild("scenario", index, true);
346         scenarioNode->setStringValue(name);
347     }
348     
349     return ok;
350 }
351
352 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
353 {
354     std::string name = args->getStringValue("name");
355     return unloadScenario(name);
356 }
357
358 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
359 {
360     addObject(definition);
361     return true;
362 }
363
364 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
365 {
366     const std::string& type = definition->getStringValue("type", "aircraft");
367     
368     FGAIBase* ai = NULL;
369     if (type == "tanker") { // refueling scenarios
370         ai = new FGAITanker; 
371     } else if (type == "wingman") {
372         ai = new FGAIWingman;
373     } else if (type == "aircraft") {
374         ai = new FGAIAircraft;
375     } else if (type == "ship") {
376         ai = new FGAIShip;
377     } else if (type == "carrier") {
378         ai = new FGAICarrier;
379     } else if (type == "groundvehicle") {
380         ai = new FGAIGroundVehicle;
381     } else if (type == "escort") {
382         ai = new FGAIEscort;
383     } else if (type == "thunderstorm") {
384         ai = new FGAIStorm;
385     } else if (type == "thermal") {
386         ai = new FGAIThermal;
387     } else if (type == "ballistic") {
388         ai = new FGAIBallistic;
389     } else if (type == "static") {
390         ai = new FGAIStatic;
391     }
392
393     ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
394     attach(ai);
395     return ai;
396 }
397
398 bool FGAIManager::removeObject(const SGPropertyNode* args)
399 {
400     int id = args->getIntValue("id");
401     BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
402         if (ai->getID() == id) {
403             ai->setDie(true);
404             break;
405         }
406     }
407     
408     return false;
409 }
410
411 bool
412 FGAIManager::loadScenario( const string &filename )
413 {
414     SGPropertyNode_ptr file = loadScenarioFile(filename);
415     if (!file) {
416         return false;
417     }
418     
419     SGPropertyNode_ptr scNode = file->getChild("scenario");
420     if (!scNode) {
421         return false;
422     }
423     
424     _scenarios[filename] = new Scenario(this, filename, scNode);
425     return true;
426 }
427
428
429 bool
430 FGAIManager::unloadScenario( const string &filename)
431 {
432     ScenarioDict::iterator it = _scenarios.find(filename);
433     if (it == _scenarios.end()) {
434         SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
435         return false;
436     }
437     
438 // remove /sim/ai node
439     unsigned int index = 0;
440     for (SGPropertyNode* n = NULL; (n = root->getChild("scenario", index)) != NULL; ++index) {
441         if (n->getStringValue() == filename) {
442             root->removeChild("scenario", index);
443             break;
444         }
445     }
446     
447     delete it->second;
448     _scenarios.erase(it);
449     return true;
450 }
451
452 void
453 FGAIManager::unloadAllScenarios()
454 {
455     ScenarioDict::iterator it = _scenarios.begin();
456     for (; it != _scenarios.end(); ++it) {
457         delete it->second;
458     } // of scenarios iteration
459     
460     
461     // remove /sim/ai node
462     root->removeChildren("scenario");
463     _scenarios.clear();
464 }
465
466
467 SGPropertyNode_ptr
468 FGAIManager::loadScenarioFile(const std::string& filename)
469 {
470     SGPath path(globals->get_fg_root());
471     path.append("AI/" + filename + ".xml");
472     try {
473         SGPropertyNode_ptr root = new SGPropertyNode;
474         readProperties(path.str(), root);
475         return root;
476     } catch (const sg_exception &t) {
477         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
478             << path.str() << "': " << t.getFormattedMessage());
479     }
480     return 0;
481 }
482
483 bool
484 FGAIManager::getStartPosition(const string& id, const string& pid,
485                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
486 {
487     bool found = false;
488     SGPropertyNode* root = fgGetNode("sim/ai", true);
489     if (!root->getNode("enabled", true)->getBoolValue())
490         return found;
491
492     for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
493         SGPropertyNode *aiEntry = root->getChild( i );
494         if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
495             const string& filename = aiEntry->getStringValue();
496             SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
497             if (scenarioTop) {
498                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
499                 if (scenarios) {
500                     for (int i = 0; i < scenarios->nChildren(); i++) {
501                         SGPropertyNode* scEntry = scenarios->getChild(i);
502                         const std::string& type = scEntry->getStringValue("type");
503                         const std::string& pnumber = scEntry->getStringValue("pennant-number");
504                         const std::string& name = scEntry->getStringValue("name");
505                         if (type == "carrier" && (pnumber == id || name == id)) {
506                             SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
507                             carrier->readFromScenario(scEntry);
508
509                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
510                                 found = true;
511                                 break;
512                             }
513                         }
514                     }
515                 }
516             }
517         }
518     }
519     return found;
520 }
521
522 const FGAIBase *
523 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
524 {
525     // we specify tgt extent (ft) according to the AIObject type
526     double tgt_ht[]     = {0,  50, 100, 250, 0, 100, 0, 0,  50,  50, 20, 100,  50};
527     double tgt_length[] = {0, 100, 200, 750, 0,  50, 0, 0, 200, 100, 40, 200, 100};
528     ai_list_iterator ai_list_itr = ai_list.begin();
529     ai_list_iterator end = ai_list.end();
530
531     SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
532     SGVec3d cartPos(SGVec3d::fromGeod(pos));
533     
534     while (ai_list_itr != end) {
535         double tgt_alt = (*ai_list_itr)->_getAltitude();
536         int type       = (*ai_list_itr)->getType();
537         tgt_ht[type] += fuse_range;
538
539         if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
540             || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
541                 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
542                 //    << fabs(tgt_alt - alt)
543                 //    << " "
544                 //    << type
545                 //    );
546                 ++ai_list_itr;
547                 continue;
548         }
549
550         int id         = (*ai_list_itr)->getID();
551
552         double range = calcRangeFt(cartPos, (*ai_list_itr));
553
554         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
555         //    << ai_list.size()
556         //    << " type " << type
557         //    << " ID " << id
558         //    << " range " << range
559         //    //<< " bearing " << bearing
560         //    << " alt " << tgt_alt
561         //    );
562
563         tgt_length[type] += fuse_range;
564
565         if (range < tgt_length[type]){
566             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
567                 << " type " << type
568                 << " ID " << id
569                 << " range " << range
570                 << " alt " << tgt_alt
571                 );
572             return (*ai_list_itr).get();
573         }
574         ++ai_list_itr;
575     }
576     return 0;
577 }
578
579 double
580 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
581 {
582     double distM = dist(aCartPos, aObject->getCartPos());
583     return distM * SG_METER_TO_FEET;
584 }
585
586 //end AIManager.cxx