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