]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
Fix stray back-button in Qt launcher
[flightgear.git] / src / AIModel / submodel.cxx
1 //// submodel.cxx - models a releasable submodel.
2 // Written by Dave Culp, started Aug 2004
3 // With major additions by Vivian Meaaza 2004 - 2007
4 //
5 // This file is in the Public Domain and comes with no warranty.
6
7 #ifdef HAVE_CONFIG_H
8 #  include "config.h"
9 #endif
10
11 #include "submodel.hxx"
12
13 #include <simgear/structure/exception.hxx>
14 #include <simgear/misc/sg_path.hxx>
15 #include <simgear/math/sg_geodesy.hxx>
16 #include <simgear/props/props_io.hxx>
17
18 #include <Main/fg_props.hxx>
19 #include <Main/util.hxx>
20
21
22 #include "AIBase.hxx"
23 #include "AIManager.hxx"
24 #include "AIBallistic.hxx"
25
26 using std::cout;
27 using std::endl;
28 using std::string;
29 using std::vector;
30
31 const double FGSubmodelMgr::lbs_to_slugs = 0.031080950172;
32
33 FGSubmodelMgr::FGSubmodelMgr()
34 {
35     x_offset = y_offset = z_offset = 0.0;
36     pitch_offset = 0.0;
37     yaw_offset = 0.0;
38
39     //out[0] = out[1] = out[2] = 0;
40     //string contents_node;
41     contrail_altitude = 30000;
42     _count = 0;
43     _found_sub = true;
44 }
45
46 FGSubmodelMgr::~FGSubmodelMgr()
47 {
48 }
49
50 FGAIManager* FGSubmodelMgr::aiManager()
51 {
52    return (FGAIManager*)globals->get_subsystem("ai-model");
53 }
54
55 void FGSubmodelMgr::init()
56 {
57     index = 0;
58
59     _serviceable_node = fgGetNode("/sim/submodels/serviceable", true);
60     _serviceable_node->setBoolValue(true);
61
62     _user_lat_node = fgGetNode("/position/latitude-deg", true);
63     _user_lon_node = fgGetNode("/position/longitude-deg", true);
64     _user_alt_node = fgGetNode("/position/altitude-ft", true);
65
66     _user_heading_node = fgGetNode("/orientation/heading-deg", true);
67     _user_pitch_node   = fgGetNode("/orientation/pitch-deg", true);
68     _user_roll_node    = fgGetNode("/orientation/roll-deg", true);
69     _user_yaw_node     = fgGetNode("/orientation/yaw-deg", true);
70     _user_alpha_node   = fgGetNode("/orientation/alpha-deg", true);
71
72     _user_speed_node = fgGetNode("/velocities/uBody-fps", true);
73
74     _user_wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps", true);
75     _user_wind_from_north_node = fgGetNode("/environment/wind-from-north-fps", true);
76
77     _user_speed_down_fps_node   = fgGetNode("/velocities/speed-down-fps", true);
78     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
79     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
80
81     _contrail_altitude_node = fgGetNode("/environment/params/contrail-altitude", true);
82     contrail_altitude       = _contrail_altitude_node->getDoubleValue();
83     _contrail_trigger       = fgGetNode("ai/submodels/contrails", true);
84     _contrail_trigger->setBoolValue(false);
85
86     load();
87 }
88
89 void FGSubmodelMgr::postinit()
90 {
91     // postinit, so that the AI list is populated
92     loadAI();
93
94     while (_found_sub)
95         loadSubmodels();
96
97     //TODO reload submodels if an MP ac joins
98
99     //_model_added_node = fgGetNode("ai/models/model-added", true);
100     //_model_added_node->addChangeListener(this, false);
101 }
102
103 void FGSubmodelMgr::bind()
104 {
105 }
106
107 void FGSubmodelMgr::unbind()
108 {
109     submodel_iterator = submodels.begin();
110     while (submodel_iterator != submodels.end()) {
111         (*submodel_iterator)->prop->untie("count");
112         ++submodel_iterator;
113     }
114 }
115
116 void FGSubmodelMgr::update(double dt)
117 {
118     if (!_serviceable_node->getBoolValue())
119         return;
120
121     _impact = false;
122     _hit = false;
123     _expiry = false;
124
125     // Check if the submodel hit an object or terrain
126     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
127     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin();
128     FGAIManager::ai_list_iterator end         = sm_list.end();
129
130     for (; sm_list_itr != end; ++sm_list_itr) {
131         FGAIBase::object_type object_type =(*sm_list_itr)->getType();
132
133         // Continue if object is not ballistic
134         if (object_type != FGAIBase::otBallistic) {
135             continue;
136         }
137
138         int parent_subID = (*sm_list_itr)->_getSubID();
139         int id = (*sm_list_itr)->getID();
140
141         if (parent_subID == 0 || id == -1) // this entry in the list has no associated submodel
142             continue;                       // or is invalid so we can continue
143
144         //SG_LOG(SG_AI, SG_DEBUG, "Submodel: Impact " << _impact << " hit! "
145         //        << _hit <<" parent_subID " << parent_subID);
146
147         _hit = (*sm_list_itr)->_getCollisionData();
148         _impact = (*sm_list_itr)->_getImpactData();
149         _expiry = (*sm_list_itr)->_getExpiryData();
150
151         //SG_LOG(SG_AI, SG_ALERT, "Submodel: " << (*sm_list_itr)->_getName()
152         //    << " Impact " << _impact << " hit! " << _hit
153         //    << " exipiry :-( " << _expiry );
154
155         if (_impact || _hit || _expiry) {
156     //        SG_LOG(SG_AI, SG_ALERT, "Submodel: Impact " << _impact << " hit! " << _hit
157                 //<< " exipiry :-( " << _expiry );
158
159             submodel_iterator = submodels.begin();
160
161             while (submodel_iterator != submodels.end()) {
162                 int child_ID = (*submodel_iterator)->id;
163                 //cout << "Impact: parent SubID " << parent_subID << " child_ID " << child_ID << endl;
164
165                 if ( parent_subID == child_ID ) {
166                     _parent_lat = (*sm_list_itr)->_getImpactLat();
167                     _parent_lon = (*sm_list_itr)->_getImpactLon();
168                     _parent_elev = (*sm_list_itr)->_getImpactElevFt();
169                     _parent_hdg = (*sm_list_itr)->_getImpactHdg();
170                     _parent_pitch = (*sm_list_itr)->_getImpactPitch();
171                     _parent_roll = (*sm_list_itr)->_getImpactRoll();
172                     _parent_speed = (*sm_list_itr)->_getImpactSpeed();
173                     (*submodel_iterator)->first_time = true;
174                     //cout << "Impact: parent SubID = child_ID elev " << _parent_elev << endl;
175
176                     if (release(*submodel_iterator, dt)) {
177                         (*sm_list_itr)->setDie(true);
178                         //cout << "Impact: set die" << (*sm_list_itr)->_getName() << endl;
179                     }
180
181                 }
182
183                 ++submodel_iterator;
184             }
185         }
186     }
187
188     _contrail_trigger->setBoolValue(_user_alt_node->getDoubleValue() > contrail_altitude);
189
190     bool trigger = false;
191     int i = -1;
192
193     submodel_iterator = submodels.begin();
194     while (submodel_iterator != submodels.end())  {
195         i++;
196
197         /*SG_LOG(SG_AI, SG_DEBUG,
198                 "Submodels:  " << (*submodel_iterator)->id
199                 << " name " << (*submodel_iterator)->name
200                 );*/
201
202         if ((*submodel_iterator)->trigger_node != 0) {
203             _trigger_node = (*submodel_iterator)->trigger_node;
204             trigger = _trigger_node->getBoolValue();
205             //cout << (*submodel_iterator)->name << "trigger node found " <<  trigger << endl;
206         }
207         else {
208             trigger = false;
209             //cout << (*submodel_iterator)->name << " trigger node not found " << trigger << endl;
210         }
211
212         if (trigger && (*submodel_iterator)->count != 0) {
213             //int id = (*submodel_iterator)->id;
214             //const string& name = (*submodel_iterator)->name;
215             
216             SG_LOG(SG_AI, SG_DEBUG,
217             "Submodels release:  " << (*submodel_iterator)->id
218             << " name " << (*submodel_iterator)->name
219             << " count " << (*submodel_iterator)->count
220             << " slaved " << (*submodel_iterator)->slaved
221             );
222
223             release(*submodel_iterator, dt);
224         } else
225             (*submodel_iterator)->first_time = true;
226
227         ++submodel_iterator;
228     }
229 }
230
231 bool FGSubmodelMgr::release(submodel *sm, double dt)
232 {
233     // Only run if first time or repeat is set to true
234     if (!sm->first_time && !sm->repeat) {
235         return false;
236     }
237
238     sm->timer += dt;
239
240     if (sm->timer < sm->delay) {
241         //cout << "not yet: timer " << sm->timer << " delay " << sm->delay << endl;
242         return false;
243     }
244
245     //cout << "released timer: " << sm->timer << " delay " << sm->delay << endl;
246
247     sm->timer = 0.0;
248
249     if (sm->first_time) {
250         dt = 0.0;
251         sm->first_time = false;
252     }
253
254     // Calculate submodel's initial conditions in world-coordinates
255     transform(sm);
256
257     FGAIBallistic* ballist = new FGAIBallistic;
258     ballist->setPath(sm->model.c_str());
259     ballist->setName(sm->name);
260     ballist->setSlaved(sm->slaved);
261     ballist->setRandom(sm->random);
262     ballist->setLifeRandomness(sm->life_randomness->get_value());
263     ballist->setLatitude(offsetpos.getLatitudeDeg());
264     ballist->setLongitude(offsetpos.getLongitudeDeg());
265     ballist->setAltitude(offsetpos.getElevationFt());
266     ballist->setAzimuthRandomError(sm->azimuth_error->get_value());
267     ballist->setAzimuth(IC.azimuth);
268     ballist->setElevationRandomError(sm->elevation_error->get_value());
269     ballist->setElevation(IC.elevation);
270     ballist->setRoll(IC.roll);
271     ballist->setSpeed(IC.speed / SG_KT_TO_FPS);
272     ballist->setWind_from_east(IC.wind_from_east);
273     ballist->setWind_from_north(IC.wind_from_north);
274     ballist->setMass(IC.mass);
275     ballist->setDragArea(sm->drag_area);
276     ballist->setLife(sm->life);
277     ballist->setBuoyancy(sm->buoyancy);
278     ballist->setWind(sm->wind);
279     ballist->setCdRandomness(sm->cd_randomness->get_value());
280     ballist->setCd(sm->cd);
281     ballist->setStabilisation(sm->aero_stabilised);
282     ballist->setNoRoll(sm->no_roll);
283     ballist->setCollision(sm->collision);
284     ballist->setExpiry(sm->expiry);
285     ballist->setImpact(sm->impact);
286     ballist->setImpactReportNode(sm->impact_report);
287     ballist->setFuseRange(sm->fuse_range);
288     ballist->setSubmodel(sm->submodel.c_str());
289     ballist->setSubID(sm->sub_id);
290     ballist->setForceStabilisation(sm->force_stabilised);
291     ballist->setExternalForce(sm->ext_force);
292     ballist->setForcePath(sm->force_path.c_str());
293     ballist->setXoffset(_x_offset);
294     ballist->setYoffset(_y_offset);
295     ballist->setZoffset(_z_offset);
296     ballist->setPitchoffset(sm->pitch_offset->get_value());
297     ballist->setYawoffset(sm->yaw_offset->get_value());
298     ballist->setParentNodes(_selected_ac);
299     ballist->setContentsNode(sm->contents_node);
300     ballist->setWeight(sm->weight);
301
302     aiManager()->attach(ballist);
303
304     if (sm->count > 0)
305         sm->count--;
306     return true;
307 }
308
309 void FGSubmodelMgr::load()
310 {
311     SGPropertyNode_ptr path_node = fgGetNode("/sim/submodels/path");
312
313     if (path_node) {
314         const int id = 0;
315         const string& path = path_node->getStringValue();
316         bool serviceable =_serviceable_node->getBoolValue();
317         setData(id, path, serviceable, "/ai/submodels/submodel", submodels);
318     }
319 }
320
321 void FGSubmodelMgr::transform(submodel *sm)
322 {
323     // Set initial conditions
324     if (sm->contents_node != 0 && !sm->slaved) {
325         // Get the weight of the contents (lbs) and convert to mass (slugs)
326         sm->contents = sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue();
327         //cout << "transform: contents " << sm->contents << endl;
328         IC.mass = (sm->weight + sm->contents) * lbs_to_slugs;
329         //cout << "mass inc contents"  << IC.mass << endl;
330
331         // Set contents to 0 in the parent
332         sm->contents_node->getChild("level-gal_us",0,1)->setDoubleValue(0);
333         /*cout << "contents " << sm->contents_node->getChild("level-gal_us")->getDoubleValue()
334         << " " << sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue()
335         << endl;*/
336     }
337     else {
338         IC.mass = sm->weight * lbs_to_slugs;
339     }
340
341     int id = sm->id;
342     //int sub_id = sm->sub_id;
343     //const string& name = sm->name;
344
345     if (sm->speed_node != 0)
346         sm->speed = sm->speed_node->getDoubleValue();
347
348     // set the Initial Conditions for the types of submodel parent 
349
350     if (_impact || _hit || _expiry) {
351         _count++;
352
353         // Set the data for a submodel tied to a submodel
354         IC.lat             = _parent_lat;
355         IC.lon             = _parent_lon;
356         IC.alt             = _parent_elev;
357         IC.roll            = _parent_roll;    // rotation about x axis
358         IC.elevation       = _parent_pitch;   // rotation about y axis
359         IC.azimuth         = _parent_hdg;     // rotation about z axis
360         IC.speed           = _parent_speed;
361         IC.speed_down_fps  = 0;
362         IC.speed_east_fps  = 0;
363         IC.speed_north_fps = 0;
364     }
365     else if (id == 0) {
366         // Set the data for a submodel tied to the main model
367         IC.lat             = _user_lat_node->getDoubleValue();
368         IC.lon             = _user_lon_node->getDoubleValue();
369         IC.alt             = _user_alt_node->getDoubleValue();
370         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
371         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
372         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
373         IC.speed           = _user_speed_node->getDoubleValue();
374         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
375         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
376         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
377     }
378     else {
379         // Set the data for a submodel tied to an AI Object
380         setParentNode(id);
381     }
382
383     // Set the Initial Conditions that are common to all types of parent
384     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
385     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
386
387     userpos.setLatitudeDeg(IC.lat);
388     userpos.setLongitudeDeg(IC.lon);
389     userpos.setElevationFt(IC.alt);
390
391     if (sm->offsets_in_meter) {
392         _x_offset = -sm->x_offset->get_value() * SG_METER_TO_FEET;
393         _y_offset =  sm->y_offset->get_value() * SG_METER_TO_FEET;
394         _z_offset =  sm->z_offset->get_value() * SG_METER_TO_FEET;
395     }
396     else {
397         _x_offset = sm->x_offset->get_value();
398         _y_offset = sm->y_offset->get_value();
399         _z_offset = sm->z_offset->get_value();
400     }
401
402     setOffsetPos();
403
404     // Compute initial orientation using yaw and pitch offsets and parent's orientation
405     const double yaw_offset = sm->yaw_offset->get_value();
406     const double pitch_offset = sm->pitch_offset->get_value();
407
408     SGQuatd ic_quat = SGQuatd::fromYawPitchRollDeg(IC.azimuth, IC.elevation, IC.roll);
409     ic_quat *= SGQuatd::fromYawPitchRollDeg(yaw_offset, pitch_offset, 0.0);
410
411     // Calculate total speed using speeds of submodel and parent
412     SGVec3d total_speed = SGVec3d(IC.speed_north_fps, IC.speed_east_fps, IC.speed_down_fps);
413     total_speed += ic_quat.rotate(SGVec3d(sm->speed, 0, 0));
414
415     IC.speed = length(total_speed);
416
417     // If speeds are low this calculation can become unreliable
418     if (IC.speed > 1) {
419         const double total_speed_north = total_speed.x();
420         const double total_speed_east  = total_speed.y();
421         const double total_speed_down  = total_speed.z();
422
423         IC.azimuth = atan2(total_speed_east, total_speed_north) * SG_RADIANS_TO_DEGREES;
424
425         // Rationalize the output
426         if (IC.azimuth < 0)
427             IC.azimuth += 360;
428         else if (IC.azimuth >= 360)
429             IC.azimuth -= 360;
430
431         IC.elevation = -atan(total_speed_down / sqrt(total_speed_north
432             * total_speed_north + total_speed_east * total_speed_east))
433             * SG_RADIANS_TO_DEGREES;
434     }
435     else {
436         double ic_roll;
437         ic_quat.getEulerDeg(IC.azimuth, IC.elevation, ic_roll);
438     }
439 }
440
441 void FGSubmodelMgr::updatelat(double lat)
442 {
443     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
444     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
445 }
446
447 void FGSubmodelMgr::loadAI()
448 {
449     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading AI submodels");
450
451     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
452
453     if (sm_list.empty()) {
454         SG_LOG(SG_AI, SG_ALERT, "Submodels: Unable to read AI submodel list");
455         return;
456     }
457
458     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin();
459     FGAIManager::ai_list_iterator end         = sm_list.end();
460
461     while (sm_list_itr != end) {
462         string path = (*sm_list_itr)->_getSMPath();
463
464         if (path.empty()) {
465             ++sm_list_itr;
466             continue;
467         }
468
469         int id = (*sm_list_itr)->getID();
470         bool serviceable = (*sm_list_itr)->_getServiceable();
471
472         //string type = (*sm_list_itr)->getTypeString();
473         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
474
475         setData(id, path, serviceable, "/ai/submodels/submodel", submodels);
476         ++sm_list_itr;
477     }
478 }
479
480 void FGSubmodelMgr::setData(int id, const string& path, bool serviceable, const string& property_path, submodel_vector_type& models)
481 {
482     SGPropertyNode root;
483
484     SGPath config = globals->resolve_aircraft_path(path);
485     try {
486         SG_LOG(SG_AI, SG_DEBUG,
487                 "Submodels: Trying to read AI submodels file: " << config.str());
488         readProperties(config.str(), &root);
489     }
490     catch (const sg_exception &) {
491         SG_LOG(SG_AI, SG_ALERT,
492                 "Submodels: Unable to read AI submodels file: " << config.str());
493         return;
494     }
495
496     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
497     vector<SGPropertyNode_ptr>::iterator it = children.begin();
498     vector<SGPropertyNode_ptr>::iterator end = children.end();
499
500     for (int i = 0; it != end; ++it, i++) {
501         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
502         submodel *sm = new submodel;
503         SGPropertyNode_ptr entry_node = *it;
504         sm->name             = entry_node->getStringValue("name", "none_defined");
505         sm->model            = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
506         sm->speed            = entry_node->getDoubleValue("speed", 2329.4);
507         sm->repeat           = entry_node->getBoolValue("repeat", false);
508         sm->delay            = entry_node->getDoubleValue("delay", 0.25);
509         sm->count            = entry_node->getIntValue("count", 1);
510         sm->slaved           = entry_node->getBoolValue("slaved", false);
511         sm->drag_area        = entry_node->getDoubleValue("eda", 0.034);
512         sm->life             = entry_node->getDoubleValue("life", 900.0);
513         sm->buoyancy         = entry_node->getDoubleValue("buoyancy", 0);
514         sm->wind             = entry_node->getBoolValue("wind", false);
515         sm->cd               = entry_node->getDoubleValue("cd", 0.193);
516         sm->weight           = entry_node->getDoubleValue("weight", 0.25);
517         sm->aero_stabilised  = entry_node->getBoolValue("aero-stabilised", true);
518         sm->no_roll          = entry_node->getBoolValue("no-roll", false);
519         sm->collision        = entry_node->getBoolValue("collision", false);
520         sm->expiry           = entry_node->getBoolValue("expiry", false);
521         sm->impact           = entry_node->getBoolValue("impact", false);
522         sm->impact_report    = entry_node->getStringValue("impact-reports");
523         sm->fuse_range       = entry_node->getDoubleValue("fuse-range", 0.0);
524         sm->contents_node    = fgGetNode(entry_node->getStringValue("contents", "none"), false);
525         sm->speed_node       = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
526         sm->submodel         = entry_node->getStringValue("submodel-path", "");
527         sm->force_stabilised = entry_node->getBoolValue("force-stabilised", false);
528         sm->ext_force        = entry_node->getBoolValue("external-force", false);
529         sm->force_path       = entry_node->getStringValue("force-path", "");
530         sm->random           = entry_node->getBoolValue("random", false);
531
532         SGPropertyNode_ptr prop_root = fgGetNode("/", true);
533         SGPropertyNode n;
534         SGPropertyNode_ptr a, b;
535
536         // Offsets
537         a = entry_node->getNode("offsets", false);
538         sm->offsets_in_meter = (a != 0);
539
540         if (a) {
541             b = a->getNode("x-m");
542             sm->x_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
543
544             b = a->getNode("y-m");
545             sm->y_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
546
547             b = a->getNode("z-m");
548             sm->z_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
549
550             b = a->getNode("heading-deg");
551             sm->yaw_offset   = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
552
553             b = a->getNode("pitch-deg");
554             sm->pitch_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
555         }
556         else {
557             bool old = false;
558
559             b = entry_node->getNode("x-offset");
560             sm->x_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
561             if (b) old = true;
562
563             b = entry_node->getNode("y-offset");
564             sm->y_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
565             if (b) old = true;
566
567             b = entry_node->getNode("z-offset");
568             sm->z_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
569             if (b) old = true;
570
571             b = entry_node->getNode("yaw-offset");
572             sm->yaw_offset   = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
573             if (b) old = true;
574
575             b = entry_node->getNode("pitch-offset");
576             sm->pitch_offset = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
577             if (b) old = true;
578
579 #if defined(ENABLE_DEV_WARNINGS)
580             if (old) {
581                 SG_LOG(SG_AI, SG_WARN, "Submodels: <*-offset> is deprecated. Use <offsets> instead");
582             }
583 #endif
584         }
585
586         // Randomness
587         a = entry_node->getNode("randomness", true);
588
589         // Maximum azimuth randomness error in degrees
590         b = a->getNode("azimuth");
591         sm->azimuth_error   = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
592
593         // Maximum elevation randomness error in degrees
594         b = a->getNode("elevation");
595         sm->elevation_error = new FGXMLAutopilot::InputValue(*prop_root, b ? *b : n);
596
597         // Randomness of Cd (plus or minus)
598         b = a->getNode("cd");
599         if (!b) {
600             b = a->getNode("cd", true);
601             b->setDoubleValue(0.1);
602         }
603         sm->cd_randomness   = new FGXMLAutopilot::InputValue(*prop_root, *b);
604
605         // Randomness of life (plus or minus)
606         b = a->getNode("life");
607         if (!b) {
608             b = a->getNode("life", true);
609             b->setDoubleValue(0.5);
610         }
611         sm->life_randomness = new FGXMLAutopilot::InputValue(*prop_root, *b);
612
613         if (sm->contents_node != 0)
614             sm->contents = sm->contents_node->getDoubleValue();
615
616         const char *trigger_path = entry_node->getStringValue("trigger", 0);
617         if (trigger_path) {
618             sm->trigger_node = fgGetNode(trigger_path, true);
619             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
620         }
621         else {
622             sm->trigger_node = 0;
623         }
624
625         if (sm->speed_node != 0)
626             sm->speed = sm->speed_node->getDoubleValue();
627
628         sm->timer = sm->delay;
629         sm->id = id;
630         sm->first_time = false;
631         sm->serviceable = serviceable;
632         sm->sub_id = 0;
633
634         sm->prop = fgGetNode(property_path, index, true);
635         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
636         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
637         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
638         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
639         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
640         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
641         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
642         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
643         const string& name = sm->name;
644         sm->prop->setStringValue("name", name.c_str());
645
646         const string& submodel = sm->submodel;
647         sm->prop->setStringValue("submodel", submodel.c_str());
648
649         const string& force_path = sm->force_path;
650         sm->prop->setStringValue("force_path", force_path.c_str());
651
652         if (sm->contents_node != 0)
653             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
654
655         index++;
656         models.push_back(sm);
657     }
658 }
659
660 void FGSubmodelMgr::loadSubmodels()
661 {
662     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading sub submodels");
663
664     _found_sub = false;
665
666     submodel_iterator = submodels.begin();
667
668     while (submodel_iterator != submodels.end()) {
669         const string& submodel  = (*submodel_iterator)->submodel;
670         if (!submodel.empty()) {
671             //int id = (*submodel_iterator)->id;
672             bool serviceable = true;
673             SG_LOG(SG_AI, SG_DEBUG, "found path sub sub "
674                     << submodel
675                     << " index " << index
676                     << " name " << (*submodel_iterator)->name);
677
678             if ((*submodel_iterator)->sub_id == 0) {
679                 (*submodel_iterator)->sub_id = index;
680                 _found_sub = true;
681                 setData(index, submodel, serviceable, "/ai/submodels/subsubmodel", subsubmodels);
682             }
683         }
684
685         ++submodel_iterator;
686     }
687
688     submodels.reserve(submodels.size() + subsubmodels.size());
689
690     // Add all elements from subsubmodels to submodels
691     subsubmodel_iterator = subsubmodels.begin();
692     while (subsubmodel_iterator != subsubmodels.end()) {
693         submodels.push_back(*subsubmodel_iterator);
694         ++subsubmodel_iterator;
695     }
696
697     subsubmodels.clear();
698 }
699
700 SGVec3d FGSubmodelMgr::getCartOffsetPos() const
701 {
702     // Convert geodetic positions to geocentered
703     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
704
705     // Transform to the right coordinate frame, configuration is done in
706     // the x-forward, y-right, z-up coordinates (feet), computation
707     // in the simulation usual body x-forward, y-right, z-down coordinates
708     // (meters) )
709     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
710         _y_offset * SG_FEET_TO_METER,
711         -_z_offset * SG_FEET_TO_METER);
712
713     // Transform the user position to the horizontal local coordinate system.
714     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
715
716     // And postrotate the orientation of the user model wrt the horizontal
717     // local frame
718     hlTrans *= SGQuatd::fromYawPitchRollDeg(
719        IC.azimuth,            
720        IC.elevation,
721        IC.roll);
722
723     // The offset converted to the usual body fixed coordinate system
724     // rotated to the earth-fixed coordinates axis
725     SGVec3d off = hlTrans.backTransform(_off);
726
727     // Add the position offset of the user model to get the geocentered position
728     SGVec3d offsetPos = cartuserPos + off;
729     return offsetPos;
730 }
731
732 void FGSubmodelMgr::setOffsetPos()
733 {
734     // Convert the offset geocentered position to geodetic
735     SGVec3d cartoffsetPos = getCartOffsetPos();
736     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
737 }
738
739 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
740 {
741     return; // this isn't working atm
742
743     const char* _model_added = _model_added_node->getStringValue();
744
745     std::basic_string <char>::size_type indexCh2b;
746
747     string str2 = _model_added;
748     const char *cstr2b = "multiplayer";
749     indexCh2b = str2.find(cstr2b, 0);
750
751     // Ignoring Ballistic Objects; there are potentially too many
752     if (indexCh2b != string::npos ) {
753         //cout << "Submodels: model added - " << str2 <<" read path "<< endl;
754         //return;
755         SGPropertyNode *a_node = fgGetNode(_model_added, true);
756         SGPropertyNode *sub_node = a_node->getChild("sim", 0, true);
757         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
758         SGPropertyNode_ptr callsign_node = a_node->getChild("callsign", 0, true);
759
760         //const string& callsign = callsign_node->getStringValue();
761         //cout << "Submodels: model added - " << callsign <<" read callsign "<< endl;
762     }
763     else {
764         cout << "model added - " << str2 <<" returning " << endl;
765     }
766 }
767
768 void FGSubmodelMgr::setParentNode(int id)
769 {
770     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
771
772     for (int i = ai->nChildren() - 1; i >= -1; i--) {
773         SGPropertyNode_ptr model;
774
775         if (i < 0) {
776             // Last iteration: selected model
777             model = _selected_ac;
778         }
779         else {
780             model = ai->getChild(i);
781             int parent_id = model->getIntValue("id");
782             if (!model->nChildren()) {
783                 continue;
784             }
785             if (parent_id == id) {
786                 // Save selected model for last iteration
787                 _selected_ac = model;
788                 break;
789             }
790         }
791         if (!model)
792             continue;
793     }
794
795     if (_selected_ac != 0) {
796         const string name  = _selected_ac->getStringValue("name");
797         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
798         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
799         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
800         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
801         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
802         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
803         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
804         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
805         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
806         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
807     }
808     else {
809         SG_LOG(SG_AI, SG_ALERT, "AISubmodel: parent node not found ");
810     }
811 }