]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
submodel: Fix randomness of Cd and life
[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->randomness);
263     ballist->setLatitude(offsetpos.getLatitudeDeg());
264     ballist->setLongitude(offsetpos.getLongitudeDeg());
265     ballist->setAltitude(offsetpos.getElevationFt());
266     ballist->setAzimuth(IC.azimuth);
267     ballist->setElevation(IC.elevation);
268     ballist->setRoll(IC.roll);
269     ballist->setSpeed(IC.speed / SG_KT_TO_FPS);
270     ballist->setWind_from_east(IC.wind_from_east);
271     ballist->setWind_from_north(IC.wind_from_north);
272     ballist->setMass(IC.mass);
273     ballist->setDragArea(sm->drag_area);
274     ballist->setLife(sm->life);
275     ballist->setBuoyancy(sm->buoyancy);
276     ballist->setWind(sm->wind);
277     ballist->setCd(sm->cd);
278     ballist->setStabilisation(sm->aero_stabilised);
279     ballist->setNoRoll(sm->no_roll);
280     ballist->setCollision(sm->collision);
281     ballist->setExpiry(sm->expiry);
282     ballist->setImpact(sm->impact);
283     ballist->setImpactReportNode(sm->impact_report);
284     ballist->setFuseRange(sm->fuse_range);
285     ballist->setSubmodel(sm->submodel.c_str());
286     ballist->setSubID(sm->sub_id);
287     ballist->setForceStabilisation(sm->force_stabilised);
288     ballist->setExternalForce(sm->ext_force);
289     ballist->setForcePath(sm->force_path.c_str());
290     ballist->setXoffset(sm->x_offset);
291     ballist->setYoffset(sm->y_offset);
292     ballist->setZoffset(sm->z_offset);
293     ballist->setPitchoffset(sm->pitch_offset->get_value());
294     ballist->setYawoffset(sm->yaw_offset->get_value());
295     ballist->setParentNodes(_selected_ac);
296     ballist->setContentsNode(sm->contents_node);
297     ballist->setWeight(sm->weight);
298
299     aiManager()->attach(ballist);
300
301     if (sm->count > 0)
302         sm->count--;
303     return true;
304 }
305
306 void FGSubmodelMgr::load()
307 {
308     SGPropertyNode_ptr path_node = fgGetNode("/sim/submodels/path");
309
310     if (path_node) {
311         const int id = 0;
312         const string& path = path_node->getStringValue();
313         bool serviceable =_serviceable_node->getBoolValue();
314         setData(id, path, serviceable, "/ai/submodels/submodel", submodels);
315     }
316 }
317
318 void FGSubmodelMgr::transform(submodel *sm)
319 {
320     // Set initial conditions
321     if (sm->contents_node != 0 && !sm->slaved) {
322         // Get the weight of the contents (lbs) and convert to mass (slugs)
323         sm->contents = sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue();
324         //cout << "transform: contents " << sm->contents << endl;
325         IC.mass = (sm->weight + sm->contents) * lbs_to_slugs;
326         //cout << "mass inc contents"  << IC.mass << endl;
327
328         // Set contents to 0 in the parent
329         sm->contents_node->getChild("level-gal_us",0,1)->setDoubleValue(0);
330         /*cout << "contents " << sm->contents_node->getChild("level-gal_us")->getDoubleValue()
331         << " " << sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue()
332         << endl;*/
333     }
334     else {
335         IC.mass = sm->weight * lbs_to_slugs;
336     }
337
338     int id = sm->id;
339     //int sub_id = sm->sub_id;
340     //const string& name = sm->name;
341
342     if (sm->speed_node != 0)
343         sm->speed = sm->speed_node->getDoubleValue();
344
345     double yaw_offset = sm->yaw_offset->get_value();
346     double pitch_offset = sm->pitch_offset->get_value();
347
348     //cout << " name " << name << " id " << id << " sub id" << sub_id << endl;
349
350     // set the Initial Conditions for the types of submodel parent 
351
352     if (_impact || _hit || _expiry) {
353         _count++;
354
355         // Set the data for a submodel tied to a submodel
356         IC.lat             = _parent_lat;
357         IC.lon             = _parent_lon;
358         IC.alt             = _parent_elev;
359         IC.roll            = _parent_roll;    // rotation about x axis
360         IC.elevation       = _parent_pitch;   // rotation about y axis
361         IC.azimuth         = _parent_hdg;     // rotation about z axis
362         IC.speed           = _parent_speed;
363         IC.speed_down_fps  = 0;
364         IC.speed_east_fps  = 0;
365         IC.speed_north_fps = 0;
366     }
367     else if (id == 0) {
368         // Set the data for a submodel tied to the main model
369         IC.lat             = _user_lat_node->getDoubleValue();
370         IC.lon             = _user_lon_node->getDoubleValue();
371         IC.alt             = _user_alt_node->getDoubleValue();
372         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
373         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
374         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
375         IC.speed           = _user_speed_node->getDoubleValue();
376         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
377         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
378         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
379     }
380     else {
381         // Set the data for a submodel tied to an AI Object
382         setParentNode(id);
383     }
384
385     //cout << "Submodel: setting IC "<< name << endl;
386     //cout << "heading " << IC.azimuth << endl ;
387     //cout << "speed down " << IC.speed_down_fps << endl ;
388     //cout << "speed east " << IC.speed_east_fps << endl ;
389     //cout << "speed north " << IC.speed_north_fps << endl ;
390     //cout << "parent speed fps in " << IC.speed << "sm speed in " << sm->speed << endl ;
391     //cout << "lat " << IC.lat;
392     //cout << "alt " << IC.alt <<  endl ;
393
394     // Set the Initial Conditions that are common to all types of parent
395     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
396     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
397
398     //cout << "wind e " << IC.wind_from_east << " n " << IC.wind_from_north << endl;
399
400     userpos.setLatitudeDeg(IC.lat);
401     userpos.setLongitudeDeg(IC.lon);
402     userpos.setElevationFt(IC.alt);
403
404     _x_offset = sm->x_offset;
405     _y_offset = sm->y_offset;
406     _z_offset = sm->z_offset;
407
408     setOffsetPos();
409
410     // Pre-process the trig functions
411     cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS);
412     sinRx = sin(-IC.roll * SG_DEGREES_TO_RADIANS);
413     cosRy = cos(-IC.elevation * SG_DEGREES_TO_RADIANS);
414     sinRy = sin(-IC.elevation * SG_DEGREES_TO_RADIANS);
415     cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS);
416     sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS);
417
418
419     // Get submodel initial velocity vector angles in XZ and XY planes.
420     // This vector should be added to aircraft's vector.
421     IC.elevation += (yaw_offset * sinRx) + (pitch_offset * cosRx);
422     IC.azimuth   += (yaw_offset * cosRx) - (pitch_offset * sinRx);
423
424     // Calculate the total speed north
425     IC.total_speed_north = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
426             * cos(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_north_fps;
427
428     // Calculate the total speed east
429     IC.total_speed_east = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
430             * sin(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_east_fps;
431
432     // Calculate the total speed down
433     IC.total_speed_down = sm->speed * -sin(IC.elevation * SG_DEGREES_TO_RADIANS)
434             + IC.speed_down_fps;
435
436     // Re-calculate speed, elevation and azimuth
437     IC.speed = sqrt(IC.total_speed_north * IC.total_speed_north
438             + IC.total_speed_east * IC.total_speed_east
439             + IC.total_speed_down * IC.total_speed_down);
440
441     // If speeds are low this calculation can become unreliable
442     if (IC.speed > 1) {
443         IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES;
444         //        cout << "azimuth1 " << IC.azimuth<<endl;
445
446         // Rationalize the output
447         if (IC.azimuth < 0)
448             IC.azimuth += 360;
449         else if (IC.azimuth >= 360)
450             IC.azimuth -= 360;
451         // cout << "azimuth2 " << IC.azimuth<<endl;
452
453         IC.elevation = -atan(IC.total_speed_down / sqrt(IC.total_speed_north
454             * IC.total_speed_north + IC.total_speed_east * IC.total_speed_east))
455             * SG_RADIANS_TO_DEGREES;
456     }
457     //cout << "IC.speed " << IC.speed / SG_KT_TO_FPS << endl;
458 }
459
460 void FGSubmodelMgr::updatelat(double lat)
461 {
462     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
463     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
464 }
465
466 void FGSubmodelMgr::loadAI()
467 {
468     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading AI submodels");
469
470     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
471
472     if (sm_list.empty()) {
473         SG_LOG(SG_AI, SG_ALERT, "Submodels: Unable to read AI submodel list");
474         return;
475     }
476
477     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin();
478     FGAIManager::ai_list_iterator end         = sm_list.end();
479
480     while (sm_list_itr != end) {
481         string path = (*sm_list_itr)->_getSMPath();
482
483         if (path.empty()) {
484             ++sm_list_itr;
485             continue;
486         }
487
488         int id = (*sm_list_itr)->getID();
489         bool serviceable = (*sm_list_itr)->_getServiceable();
490
491         //string type = (*sm_list_itr)->getTypeString();
492         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
493
494         setData(id, path, serviceable, "/ai/submodels/submodel", submodels);
495         ++sm_list_itr;
496     }
497 }
498
499 void FGSubmodelMgr::setData(int id, const string& path, bool serviceable, const string& property_path, submodel_vector_type& models)
500 {
501     SGPropertyNode root;
502
503     SGPath config = globals->resolve_aircraft_path(path);
504     try {
505         SG_LOG(SG_AI, SG_DEBUG,
506                 "Submodels: Trying to read AI submodels file: " << config.str());
507         readProperties(config.str(), &root);
508     }
509     catch (const sg_exception &) {
510         SG_LOG(SG_AI, SG_ALERT,
511                 "Submodels: Unable to read AI submodels file: " << config.str());
512         return;
513     }
514
515     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
516     vector<SGPropertyNode_ptr>::iterator it = children.begin();
517     vector<SGPropertyNode_ptr>::iterator end = children.end();
518
519     for (int i = 0; it != end; ++it, i++) {
520         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
521         submodel *sm = new submodel;
522         SGPropertyNode_ptr entry_node = *it;
523         sm->name             = entry_node->getStringValue("name", "none_defined");
524         sm->model            = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
525         sm->speed            = entry_node->getDoubleValue("speed", 2329.4);
526         sm->repeat           = entry_node->getBoolValue("repeat", false);
527         sm->delay            = entry_node->getDoubleValue("delay", 0.25);
528         sm->count            = entry_node->getIntValue("count", 1);
529         sm->slaved           = entry_node->getBoolValue("slaved", false);
530         sm->x_offset         = entry_node->getDoubleValue("x-offset", 0.0);
531         sm->y_offset         = entry_node->getDoubleValue("y-offset", 0.0);
532         sm->z_offset         = entry_node->getDoubleValue("z-offset", 0.0);
533         sm->drag_area        = entry_node->getDoubleValue("eda", 0.034);
534         sm->life             = entry_node->getDoubleValue("life", 900.0);
535         sm->buoyancy         = entry_node->getDoubleValue("buoyancy", 0);
536         sm->wind             = entry_node->getBoolValue("wind", false);
537         sm->cd               = entry_node->getDoubleValue("cd", 0.193);
538         sm->weight           = entry_node->getDoubleValue("weight", 0.25);
539         sm->aero_stabilised  = entry_node->getBoolValue("aero-stabilised", true);
540         sm->no_roll          = entry_node->getBoolValue("no-roll", false);
541         sm->collision        = entry_node->getBoolValue("collision", false);
542         sm->expiry           = entry_node->getBoolValue("expiry", false);
543         sm->impact           = entry_node->getBoolValue("impact", false);
544         sm->impact_report    = entry_node->getStringValue("impact-reports");
545         sm->fuse_range       = entry_node->getDoubleValue("fuse-range", 0.0);
546         sm->contents_node    = fgGetNode(entry_node->getStringValue("contents", "none"), false);
547         sm->speed_node       = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
548         sm->submodel         = entry_node->getStringValue("submodel-path", "");
549         sm->force_stabilised = entry_node->getBoolValue("force-stabilised", false);
550         sm->ext_force        = entry_node->getBoolValue("external-force", false);
551         sm->force_path       = entry_node->getStringValue("force-path", "");
552         sm->random           = entry_node->getBoolValue("random", false);
553         sm->randomness       = entry_node->getDoubleValue("randomness", 0.5);
554
555         SGPropertyNode_ptr prop_root = fgGetNode("/", true);
556         SGPropertyNode n;
557
558         SGPropertyNode_ptr a = entry_node->getNode("yaw-offset");
559         sm->yaw_offset   = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
560
561         a = entry_node->getNode("pitch-offset");
562         sm->pitch_offset = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
563
564         if (sm->contents_node != 0)
565             sm->contents = sm->contents_node->getDoubleValue();
566
567         const char *trigger_path = entry_node->getStringValue("trigger", 0);
568         if (trigger_path) {
569             sm->trigger_node = fgGetNode(trigger_path, true);
570             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
571         }
572         else {
573             sm->trigger_node = 0;
574         }
575
576         if (sm->speed_node != 0)
577             sm->speed = sm->speed_node->getDoubleValue();
578
579         sm->timer = sm->delay;
580         sm->id = id;
581         sm->first_time = false;
582         sm->serviceable = serviceable;
583         sm->sub_id = 0;
584
585         sm->prop = fgGetNode(property_path, index, true);
586         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
587         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
588         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
589         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
590         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
591         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
592         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
593         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
594         const string& name = sm->name;
595         sm->prop->setStringValue("name", name.c_str());
596
597         const string& submodel = sm->submodel;
598         sm->prop->setStringValue("submodel", submodel.c_str());
599
600         const string& force_path = sm->force_path;
601         sm->prop->setStringValue("force_path", force_path.c_str());
602
603         if (sm->contents_node != 0)
604             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
605
606         index++;
607         models.push_back(sm);
608     }
609 }
610
611 void FGSubmodelMgr::loadSubmodels()
612 {
613     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading sub submodels");
614
615     _found_sub = false;
616
617     submodel_iterator = submodels.begin();
618
619     while (submodel_iterator != submodels.end()) {
620         const string& submodel  = (*submodel_iterator)->submodel;
621         if (!submodel.empty()) {
622             //int id = (*submodel_iterator)->id;
623             bool serviceable = true;
624             SG_LOG(SG_AI, SG_DEBUG, "found path sub sub "
625                     << submodel
626                     << " index " << index
627                     << " name " << (*submodel_iterator)->name);
628
629             if ((*submodel_iterator)->sub_id == 0) {
630                 (*submodel_iterator)->sub_id = index;
631                 _found_sub = true;
632                 setData(index, submodel, serviceable, "/ai/submodels/subsubmodel", subsubmodels);
633             }
634         }
635
636         ++submodel_iterator;
637     }
638
639     submodels.reserve(submodels.size() + subsubmodels.size());
640
641     // Add all elements from subsubmodels to submodels
642     subsubmodel_iterator = subsubmodels.begin();
643     while (subsubmodel_iterator != subsubmodels.end()) {
644         submodels.push_back(*subsubmodel_iterator);
645         ++subsubmodel_iterator;
646     }
647
648     subsubmodels.clear();
649 }
650
651 SGVec3d FGSubmodelMgr::getCartOffsetPos() const
652 {
653     // Convert geodetic positions to geocentered
654     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
655
656     // Transform to the right coordinate frame, configuration is done in
657     // the x-forward, y-right, z-up coordinates (feet), computation
658     // in the simulation usual body x-forward, y-right, z-down coordinates
659     // (meters) )
660     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
661         _y_offset * SG_FEET_TO_METER,
662         -_z_offset * SG_FEET_TO_METER);
663
664     // Transform the user position to the horizontal local coordinate system.
665     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
666
667     // And postrotate the orientation of the user model wrt the horizontal
668     // local frame
669     hlTrans *= SGQuatd::fromYawPitchRollDeg(
670        IC.azimuth,            
671        IC.elevation,
672        IC.roll);
673
674     // The offset converted to the usual body fixed coordinate system
675     // rotated to the earth-fixed coordinates axis
676     SGVec3d off = hlTrans.backTransform(_off);
677
678     // Add the position offset of the user model to get the geocentered position
679     SGVec3d offsetPos = cartuserPos + off;
680     return offsetPos;
681 }
682
683 void FGSubmodelMgr::setOffsetPos()
684 {
685     // Convert the offset geocentered position to geodetic
686     SGVec3d cartoffsetPos = getCartOffsetPos();
687     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
688 }
689
690 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
691 {
692     return; // this isn't working atm
693
694     const char* _model_added = _model_added_node->getStringValue();
695
696     std::basic_string <char>::size_type indexCh2b;
697
698     string str2 = _model_added;
699     const char *cstr2b = "multiplayer";
700     indexCh2b = str2.find(cstr2b, 0);
701
702     // Ignoring Ballistic Objects; there are potentially too many
703     if (indexCh2b != string::npos ) {
704         //cout << "Submodels: model added - " << str2 <<" read path "<< endl;
705         //return;
706         SGPropertyNode *a_node = fgGetNode(_model_added, true);
707         SGPropertyNode *sub_node = a_node->getChild("sim", 0, true);
708         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
709         SGPropertyNode_ptr callsign_node = a_node->getChild("callsign", 0, true);
710
711         //const string& callsign = callsign_node->getStringValue();
712         //cout << "Submodels: model added - " << callsign <<" read callsign "<< endl;
713     }
714     else {
715         cout << "model added - " << str2 <<" returning " << endl;
716     }
717 }
718
719 void FGSubmodelMgr::setParentNode(int id)
720 {
721     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
722
723     for (int i = ai->nChildren() - 1; i >= -1; i--) {
724         SGPropertyNode_ptr model;
725
726         if (i < 0) {
727             // Last iteration: selected model
728             model = _selected_ac;
729         }
730         else {
731             model = ai->getChild(i);
732             int parent_id = model->getIntValue("id");
733             if (!model->nChildren()) {
734                 continue;
735             }
736             if (parent_id == id) {
737                 // Save selected model for last iteration
738                 _selected_ac = model;
739                 break;
740             }
741         }
742         if (!model)
743             continue;
744     }
745
746     if (_selected_ac != 0) {
747         const string name  = _selected_ac->getStringValue("name");
748         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
749         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
750         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
751         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
752         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
753         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
754         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
755         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
756         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
757         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
758     }
759     else {
760         SG_LOG(SG_AI, SG_ALERT, "AISubmodel: parent node not found ");
761     }
762 }