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