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