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