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