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