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