]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
#248: support enabling AI module at run-time
[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
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/props/props_io.hxx>
25 #include <simgear/structure/exception.hxx>
26
27 #include <Main/globals.hxx>
28
29 #include <Airports/simple.hxx>
30 #include <Traffic/TrafficMgr.hxx>
31
32 #include "AIManager.hxx"
33 #include "AIAircraft.hxx"
34 #include "AIShip.hxx"
35 #include "AIBallistic.hxx"
36 #include "AIStorm.hxx"
37 #include "AIThermal.hxx"
38 #include "AICarrier.hxx"
39 #include "AIStatic.hxx"
40 #include "AIMultiplayer.hxx"
41 #include "AITanker.hxx"
42 #include "AIWingman.hxx"
43 #include "AIGroundVehicle.hxx"
44 #include "AIEscort.hxx"
45
46 FGAIManager::FGAIManager() :
47     cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
48                fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
49     cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
50                    fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
51 {
52     _dt = 0.0;
53     mNumAiModels = 0;
54
55     for (unsigned i = 0; i < FGAIBase::MAX_OBJECTS; ++i)
56         mNumAiTypeModels[i] = 0;
57 }
58
59 FGAIManager::~FGAIManager() {
60     ai_list_iterator ai_list_itr = ai_list.begin();
61
62     while(ai_list_itr != ai_list.end()) {
63         (*ai_list_itr)->unbind();
64         ++ai_list_itr;
65     }
66 }
67
68 void
69 FGAIManager::init() {
70     root = fgGetNode("sim/ai", true);
71
72     enabled = root->getNode("enabled", true);
73
74     thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
75     wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps",true);
76     wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
77
78     user_latitude_node  = fgGetNode("/position/latitude-deg", true);
79     user_longitude_node = fgGetNode("/position/longitude-deg", true);
80     user_altitude_node  = fgGetNode("/position/altitude-ft", true);
81     user_altitude_agl_node  = fgGetNode("/position/altitude-agl-ft", true);
82     user_heading_node   = fgGetNode("/orientation/heading-deg", true);
83     user_pitch_node     = fgGetNode("/orientation/pitch-deg", true);
84     user_yaw_node       = fgGetNode("/orientation/side-slip-deg", true);
85     user_roll_node      = fgGetNode("/orientation/roll-deg", true);
86     user_speed_node     = fgGetNode("/velocities/uBody-fps", true);
87 }
88
89 void
90 FGAIManager::postinit() {
91     // postinit, so that it can access the Nasal subsystem
92     map<string, bool> scenarios;
93     for (int i = 0 ; i < root->nChildren() ; i++) {
94         SGPropertyNode *n = root->getChild(i);
95         if (strcmp(n->getName(), "scenario"))
96             continue;
97
98         string name = n->getStringValue();
99         if (name.empty())
100             continue;
101
102         if (scenarios.find(name) != scenarios.end()) {
103             SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
104             continue;
105         }
106
107         SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
108         processScenario(name);
109         scenarios[name] = true;
110     }
111 }
112
113 void
114 FGAIManager::reinit() {
115     update(0.0);
116
117     ai_list_iterator ai_list_itr = ai_list.begin();
118
119     while(ai_list_itr != ai_list.end()) {
120         (*ai_list_itr)->reinit();
121         ++ai_list_itr;
122     }
123 }
124
125 void
126 FGAIManager::bind() {
127     root = globals->get_props()->getNode("ai/models", true);
128     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
129         &FGAIManager::getNumAiObjects));
130 }
131
132 void
133 FGAIManager::unbind() {
134     root->untie("count");
135 }
136
137 void
138 FGAIManager::update(double dt) {
139     // initialize these for finding nearest thermals
140     range_nearest = 10000.0;
141     strength = 0.0;
142
143     if (!enabled->getBoolValue())
144         return;
145
146     FGTrafficManager *tmgr = (FGTrafficManager*) globals->get_subsystem("traffic-manager");
147     _dt = dt;
148
149     ai_list_iterator ai_list_itr = ai_list.begin();
150
151     while(ai_list_itr != ai_list.end()) {
152
153         if ((*ai_list_itr)->getDie()) {
154             tmgr->release((*ai_list_itr)->getID());
155             --mNumAiModels;
156             --(mNumAiTypeModels[(*ai_list_itr)->getType()]);
157             FGAIBase *base = (*ai_list_itr).get();
158             SGPropertyNode *props = base->_getProps();
159
160             props->setBoolValue("valid", false);
161             base->unbind();
162
163             // for backward compatibility reset properties, so that aircraft,
164             // which don't know the <valid> property, keep working
165             // TODO: remove after a while
166             props->setIntValue("id", -1);
167             props->setBoolValue("radar/in-range", false);
168             props->setIntValue("refuel/tanker", false);
169
170             ai_list_itr = ai_list.erase(ai_list_itr);
171         } else {
172             fetchUserState();
173             if ((*ai_list_itr)->isa(FGAIBase::otThermal)) {
174                 FGAIBase *base = (*ai_list_itr).get();
175                 processThermal((FGAIThermal*)base);
176             } else {
177                 (*ai_list_itr)->update(_dt);
178             }
179             ++ai_list_itr;
180         }
181     }
182
183     thermal_lift_node->setDoubleValue( strength );  // for thermals
184 }
185
186 /** update LOD settings of all AI/MP models */
187 void
188 FGAIManager::updateLOD(SGPropertyNode* node)
189 {
190     ai_list_iterator ai_list_itr = ai_list.begin();
191     while(ai_list_itr != ai_list.end())
192     {
193         (*ai_list_itr)->updateLOD();
194         ++ai_list_itr;
195     }
196 }
197
198 void
199 FGAIManager::attach(FGAIBase *model)
200 {
201     //unsigned idx = mNumAiTypeModels[model->getType()];
202     const char* typeString = model->getTypeString();
203     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
204     SGPropertyNode* p;
205     int i;
206
207     // find free index in the property tree, if we have
208     // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
209     for (i = 0; i < 10000; i++) {
210         p = root->getNode(typeString, i, false);
211
212         if (!p || !p->getBoolValue("valid", false))
213             break;
214
215         if (p->getIntValue("id",-1)==model->getID()) {
216             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
217         }
218     }
219
220     p = root->getNode(typeString, i, true);
221     model->setManager(this, p);
222     ai_list.push_back(model);
223     ++mNumAiModels;
224     ++(mNumAiTypeModels[model->getType()]);
225     model->init(model->getType()==FGAIBase::otAircraft
226         || model->getType()==FGAIBase::otMultiplayer
227         || model->getType()==FGAIBase::otStatic);
228     model->bind();
229     p->setBoolValue("valid", true);
230 }
231
232 void
233 FGAIManager::destroyObject( int ID ) {
234     ai_list_iterator ai_list_itr = ai_list.begin();
235
236     while(ai_list_itr != ai_list.end()) {
237
238         if ((*ai_list_itr)->getID() == ID) {
239             --mNumAiModels;
240             --(mNumAiTypeModels[(*ai_list_itr)->getType()]);
241             (*ai_list_itr)->unbind();
242             ai_list_itr = ai_list.erase(ai_list_itr);
243         } else
244             ++ai_list_itr;
245     }
246
247 }
248
249 int
250 FGAIManager::getNumAiObjects(void) const
251 {
252     return mNumAiModels;
253 }
254
255 void
256 FGAIManager::fetchUserState( void ) {
257
258     user_latitude  = user_latitude_node->getDoubleValue();
259     user_longitude = user_longitude_node->getDoubleValue();
260     user_altitude  = user_altitude_node->getDoubleValue();
261     user_heading   = user_heading_node->getDoubleValue();
262     user_pitch     = user_pitch_node->getDoubleValue();
263     user_yaw       = user_yaw_node->getDoubleValue();
264     user_speed     = user_speed_node->getDoubleValue() * 0.592484;
265     user_roll      = user_roll_node->getDoubleValue();
266     wind_from_east = wind_from_east_node->getDoubleValue();
267     wind_from_north   = wind_from_north_node->getDoubleValue();
268     user_altitude_agl = user_altitude_agl_node->getDoubleValue();
269
270 }
271
272 // only keep the results from the nearest thermal
273 void
274 FGAIManager::processThermal( FGAIThermal* thermal ) {
275     thermal->update(_dt);
276
277     if ( thermal->_getRange() < range_nearest ) {
278         range_nearest = thermal->_getRange();
279         strength = thermal->getStrength();
280     }
281
282 }
283
284
285
286 void
287 FGAIManager::processScenario( const string &filename ) {
288
289     SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
290
291     if (!scenarioTop)
292         return;
293
294     SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
295
296     if (!scenarios)
297         return;
298
299     for (int i = 0; i < scenarios->nChildren(); i++) {
300         SGPropertyNode* scEntry = scenarios->getChild(i);
301
302         if (strcmp(scEntry->getName(), "entry"))
303             continue;
304         std::string type = scEntry->getStringValue("type", "aircraft");
305
306         if (type == "tanker") { // refueling scenarios
307             FGAITanker* tanker = new FGAITanker;
308             tanker->readFromScenario(scEntry);
309             attach(tanker);
310
311         } else if (type == "wingman") {
312             FGAIWingman* wingman = new FGAIWingman;
313             wingman->readFromScenario(scEntry);
314             attach(wingman);
315
316         } else if (type == "aircraft") {
317             FGAIAircraft* aircraft = new FGAIAircraft;
318             aircraft->readFromScenario(scEntry);
319             attach(aircraft);
320
321         } else if (type == "ship") {
322             FGAIShip* ship = new FGAIShip;
323             ship->readFromScenario(scEntry);
324             attach(ship);
325
326         } else if (type == "carrier") {
327             FGAICarrier* carrier = new FGAICarrier;
328             carrier->readFromScenario(scEntry);
329             attach(carrier);
330
331         } else if (type == "groundvehicle") {
332             FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
333             groundvehicle->readFromScenario(scEntry);
334             attach(groundvehicle);
335
336         } else if (type == "escort") {
337             FGAIEscort* escort = new FGAIEscort;
338             escort->readFromScenario(scEntry);
339             attach(escort);
340
341         } else if (type == "thunderstorm") {
342             FGAIStorm* storm = new FGAIStorm;
343             storm->readFromScenario(scEntry);
344             attach(storm);
345
346         } else if (type == "thermal") {
347             FGAIThermal* thermal = new FGAIThermal;
348             thermal->readFromScenario(scEntry);
349             attach(thermal);
350
351         } else if (type == "ballistic") {
352             FGAIBallistic* ballistic = new FGAIBallistic;
353             ballistic->readFromScenario(scEntry);
354             attach(ballistic);
355
356         } else if (type == "static") {
357             FGAIStatic* aistatic = new FGAIStatic;
358             aistatic->readFromScenario(scEntry);
359             attach(aistatic);
360         }
361
362     }
363
364 }
365
366 SGPropertyNode_ptr
367 FGAIManager::loadScenarioFile(const std::string& filename)
368 {
369     SGPath path(globals->get_fg_root());
370     path.append("AI/" + filename + ".xml");
371     try {
372         SGPropertyNode_ptr root = new SGPropertyNode;
373         readProperties(path.str(), root);
374         return root;
375     } catch (const sg_exception &t) {
376         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
377             << path.str() << "': " << t.getFormattedMessage());
378         return 0;
379     }
380 }
381
382 bool
383 FGAIManager::getStartPosition(const string& id, const string& pid,
384                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
385 {
386     bool found = false;
387     SGPropertyNode* root = fgGetNode("sim/ai", true);
388     if (!root->getNode("enabled", true)->getBoolValue())
389         return found;
390
391     for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
392         SGPropertyNode *aiEntry = root->getChild( i );
393         if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
394             string filename = aiEntry->getStringValue();
395             SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
396             if (scenarioTop) {
397                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
398                 if (scenarios) {
399                     for (int i = 0; i < scenarios->nChildren(); i++) {
400                         SGPropertyNode* scEntry = scenarios->getChild(i);
401                         std::string type = scEntry->getStringValue("type");
402                         std::string pnumber = scEntry->getStringValue("pennant-number");
403                         std::string name = scEntry->getStringValue("name");
404                         if (type == "carrier" && (pnumber == id || name == id)) {
405                             SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
406                             carrier->readFromScenario(scEntry);
407
408                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
409                                 found = true;
410                                 break;
411                             }
412                         }
413                     }
414                 }
415             }
416         }
417     }
418     return found;
419 }
420
421 const FGAIBase *
422 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
423 {
424     // we specify tgt extent (ft) according to the AIObject type
425     double tgt_ht[]     = {0,  50, 100, 250, 0, 100, 0, 0,  50,  50, 20, 100,  50};
426     double tgt_length[] = {0, 100, 200, 750, 0,  50, 0, 0, 200, 100, 40, 200, 100};
427     ai_list_iterator ai_list_itr = ai_list.begin();
428     ai_list_iterator end = ai_list.end();
429
430     while (ai_list_itr != end) {
431         double tgt_alt = (*ai_list_itr)->_getAltitude();
432         int type       = (*ai_list_itr)->getType();
433         tgt_ht[type] += fuse_range;
434
435         if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
436             || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
437                 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
438                 //    << fabs(tgt_alt - alt)
439                 //    << " "
440                 //    << type
441                 //    );
442                 ++ai_list_itr;
443                 continue;
444         }
445
446         double tgt_lat = (*ai_list_itr)->_getLatitude();
447         double tgt_lon = (*ai_list_itr)->_getLongitude();
448         int id         = (*ai_list_itr)->getID();
449
450         double range = calcRange(lat, lon, tgt_lat, tgt_lon);
451
452         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
453         //    << ai_list.size()
454         //    << " type " << type
455         //    << " ID " << id
456         //    << " range " << range
457         //    //<< " bearing " << bearing
458         //    << " alt " << tgt_alt
459         //    );
460
461         tgt_length[type] += fuse_range;
462
463         if (range < tgt_length[type]){
464             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
465                 << " type " << type
466                 << " ID " << id
467                 << " range " << range
468                 << " alt " << tgt_alt
469                 );
470             return (*ai_list_itr).get();
471         }
472         ++ai_list_itr;
473     }
474     return 0;
475 }
476
477 double
478 FGAIManager::calcRange(double lat, double lon, double lat2, double lon2) const
479 {
480     double course, az2, distance;
481
482     //calculate the bearing and range of the second pos from the first
483     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
484     distance *= SG_METER_TO_FEET;
485     return distance;
486 }
487
488 //end AIManager.cxx