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