]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
Improve transponder instrumentation: new version
[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
90 void FGSubmodelMgr::postinit() {
91     // postinit, so that the AI list is populated
92
93         loadAI();
94
95     while (_found_sub)
96         loadSubmodels();
97
98     //TODO reload submodels if an MP ac joins
99
100     //_model_added_node = fgGetNode("ai/models/model-added", true);
101     //_model_added_node->addChangeListener(this, false);
102 }
103
104 void FGSubmodelMgr::bind()
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       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         if (object_type != FGAIBase::otBallistic){// only work on ballistic objects
134             continue; // so continue 
135         }
136
137         int parent_subID = (*sm_list_itr)->_getSubID();
138         int id = (*sm_list_itr)->getID();
139
140         if ( parent_subID == 0 || id == -1) // this entry in the list has no associated submodel
141             continue;                       // or is invalid so we can continue
142
143         //SG_LOG(SG_AI, SG_DEBUG, "Submodel: Impact " << _impact << " hit! "
144         //        << _hit <<" parent_subID " << parent_subID);
145
146         _hit = (*sm_list_itr)->_getCollisionData();
147         _impact = (*sm_list_itr)->_getImpactData();
148         _expiry = (*sm_list_itr)->_getExpiryData();
149
150         //SG_LOG(SG_AI, SG_ALERT, "Submodel: " << (*sm_list_itr)->_getName()
151         //    << " Impact " << _impact << " hit! " << _hit
152         //    << " exipiry :-( " << _expiry );
153
154         if (_impact || _hit || _expiry) {
155     //        SG_LOG(SG_AI, SG_ALERT, "Submodel: Impact " << _impact << " hit! " << _hit
156                 //<< " exipiry :-( " << _expiry );
157
158             submodel_iterator = submodels.begin();
159
160             while (submodel_iterator != submodels.end()) {
161                 int child_ID = (*submodel_iterator)->id;
162                 //cout << "Impact: parent SubID " << parent_subID << " child_ID " << child_ID << endl;
163
164                 if ( parent_subID == child_ID ) {
165                     _parent_lat = (*sm_list_itr)->_getImpactLat();
166                     _parent_lon = (*sm_list_itr)->_getImpactLon();
167                     _parent_elev = (*sm_list_itr)->_getImpactElevFt();
168                     _parent_hdg = (*sm_list_itr)->_getImpactHdg();
169                     _parent_pitch = (*sm_list_itr)->_getImpactPitch();
170                     _parent_roll = (*sm_list_itr)->_getImpactRoll();
171                     _parent_speed = (*sm_list_itr)->_getImpactSpeed();
172                     (*submodel_iterator)->first_time = true;
173                     //cout << "Impact: parent SubID = child_ID elev " << _parent_elev << endl;
174
175                     if (release(*submodel_iterator, dt)){
176                         (*sm_list_itr)->setDie(true);
177                         //cout << "Impact: set die" << (*sm_list_itr)->_getName() << endl;
178                     }
179
180                 }
181
182                 ++submodel_iterator;
183             }
184         }
185     }
186
187     _contrail_trigger->setBoolValue(_user_alt_node->getDoubleValue() > contrail_altitude);
188
189
190 //    bool in_range = true;
191     bool trigger = false;
192     int i = -1;
193
194     submodel_iterator = submodels.begin();
195     while (submodel_iterator != submodels.end())  {
196         i++;
197
198         /*SG_LOG(SG_AI, SG_DEBUG,
199                 "Submodels:  " << (*submodel_iterator)->id
200                 << " name " << (*submodel_iterator)->name
201                 );*/
202
203         if ((*submodel_iterator)->trigger_node != 0) {
204             _trigger_node = (*submodel_iterator)->trigger_node;
205             trigger = _trigger_node->getBoolValue();
206             //cout << (*submodel_iterator)->name << "trigger node found " <<  trigger << endl;
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
214             //int id = (*submodel_iterator)->id;
215             //const string& name = (*submodel_iterator)->name;
216             
217             SG_LOG(SG_AI, SG_DEBUG,
218             "Submodels release:  " << (*submodel_iterator)->id
219             << " name " << (*submodel_iterator)->name
220             << " count " << (*submodel_iterator)->count
221             << " slaved " << (*submodel_iterator)->slaved
222             );
223
224             release(*submodel_iterator, dt);
225         } else
226             (*submodel_iterator)->first_time = true;
227
228         ++submodel_iterator;
229     } // end while
230 }
231
232 bool FGSubmodelMgr::release(submodel *sm, double dt)
233 {
234     //cout << "release id " << sm->id 
235     //    << " name " << sm->name
236     //    << " first time " << sm->first_time
237     //    << " repeat " << sm->repeat
238     //    << " slaved " << sm->slaved
239     //    << endl;
240
241     // only run if first time or repeat is set to true
242     if (!sm->first_time && !sm->repeat) {
243         //cout<< "returning: "<< sm->name 
244         //    << " not first time " << sm->first_time 
245         //    << " repeat " << sm->repeat
246         //    << " slaved " << sm->slaved
247         //    << endl;
248         return false;
249     }
250
251     sm->timer += dt;
252
253     if (sm->timer < sm->delay) {
254         //cout << "not yet: timer " << sm->timer << " delay " << sm->delay << endl;
255         return false;
256     }
257     
258     //cout << "released timer: " << sm->timer << " delay " << sm->delay << endl;
259
260     sm->timer = 0.0;
261
262     if (sm->first_time) {
263         dt = 0.0;
264         sm->first_time = false;
265     }
266
267     transform(sm);  // calculate submodel's initial conditions in world-coordinates
268
269     FGAIBallistic* ballist = new FGAIBallistic;
270     ballist->setPath(sm->model.c_str());
271     ballist->setName(sm->name);
272     ballist->setSlaved(sm->slaved);
273     ballist->setRandom(sm->random);
274     ballist->setRandomness(sm->randomness);
275     ballist->setLatitude(offsetpos.getLatitudeDeg());
276     ballist->setLongitude(offsetpos.getLongitudeDeg());
277     ballist->setAltitude(offsetpos.getElevationFt());
278     ballist->setAzimuth(IC.azimuth);
279     ballist->setElevation(IC.elevation);
280     ballist->setRoll(IC.roll);
281     ballist->setSpeed(IC.speed / SG_KT_TO_FPS);
282     ballist->setWind_from_east(IC.wind_from_east);
283     ballist->setWind_from_north(IC.wind_from_north);
284     ballist->setMass(IC.mass);
285     ballist->setDragArea(sm->drag_area);
286     ballist->setLife(sm->life);
287     ballist->setBuoyancy(sm->buoyancy);
288     ballist->setWind(sm->wind);
289     ballist->setCd(sm->cd);
290     ballist->setStabilisation(sm->aero_stabilised);
291     ballist->setNoRoll(sm->no_roll);
292     ballist->setCollision(sm->collision);
293     ballist->setExpiry(sm->expiry);
294     ballist->setImpact(sm->impact);
295     ballist->setImpactReportNode(sm->impact_report);
296     ballist->setFuseRange(sm->fuse_range);
297     ballist->setSubmodel(sm->submodel.c_str());
298     ballist->setSubID(sm->sub_id);
299     ballist->setForceStabilisation(sm->force_stabilised);
300     ballist->setExternalForce(sm->ext_force);
301     ballist->setForcePath(sm->force_path.c_str());
302     ballist->setXoffset(sm->x_offset);
303     ballist->setYoffset(sm->y_offset);
304     ballist->setZoffset(sm->z_offset);
305     ballist->setPitchoffset(sm->pitch_offset);
306     ballist->setYawoffset(sm->yaw_offset);
307     ballist->setParentNodes(_selected_ac);
308     ballist->setContentsNode(sm->contents_node);
309     ballist->setWeight(sm->weight);
310     
311     aiManager()->attach(ballist);
312
313     if (sm->count > 0)
314         sm->count--;
315     return true;
316 }
317
318 void FGSubmodelMgr::load()
319 {
320     SGPropertyNode *path = fgGetNode("/sim/submodels/path");
321
322     if (path) {
323         const int id = 0;
324         const string& Path = path->getStringValue();
325         bool Seviceable =_serviceable_node->getBoolValue();
326         setData(id, Path, Seviceable);
327     }
328 }
329
330 void FGSubmodelMgr::transform(submodel *sm)
331 {
332     // set initial conditions
333     if (sm->contents_node != 0 && !sm->slaved) {
334         // get the weight of the contents (lbs) and convert to mass (slugs)
335         sm->contents = sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue();
336         //cout << "transform: contents " << sm->contents << endl;
337         IC.mass = (sm->weight + sm->contents) * lbs_to_slugs;
338         //cout << "mass inc contents"  << IC.mass << endl;
339
340         // set contents to 0 in the parent
341         sm->contents_node->getChild("level-gal_us",0,1)->setDoubleValue(0);
342         /*cout << "contents " << sm->contents_node->getChild("level-gal_us")->getDoubleValue()
343         << " " << sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue()
344         << endl;*/
345     } else
346         IC.mass = sm->weight * lbs_to_slugs;
347
348     int id = sm->id;
349     //int sub_id = sm->sub_id;
350     //const string& name = sm->name;
351
352
353     if (sm->speed_node != 0)
354         sm->speed = sm->speed_node->getDoubleValue();
355
356
357     //cout << " name " << name << " id " << id << " sub id" << sub_id << endl;
358
359     // set the Initial Conditions for the types of submodel parent 
360
361     if (_impact || _hit || _expiry) {
362         // set the data for a submodel tied to a submodel
363
364         _count++;
365
366         IC.lat             = _parent_lat;
367         IC.lon             = _parent_lon;
368         IC.alt             = _parent_elev;
369         IC.roll            = _parent_roll;    // rotation about x axis
370         IC.elevation       = _parent_pitch;   // rotation about y axis
371         IC.azimuth         = _parent_hdg;     // rotation about z axis
372         IC.speed           = _parent_speed;
373         IC.speed_down_fps  = 0;
374         IC.speed_east_fps  = 0;
375         IC.speed_north_fps = 0;
376
377     } else if (id == 0) {
378         //set the data for a submodel tied to the main model
379
380         IC.lat             = _user_lat_node->getDoubleValue();
381         IC.lon             = _user_lon_node->getDoubleValue();
382         IC.alt             = _user_alt_node->getDoubleValue();
383         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
384         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
385         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
386         IC.speed           = _user_speed_node->getDoubleValue();
387         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
388         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
389         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
390
391     } else {
392         // set the data for a submodel tied to an AI Object
393         //cout << " set the data for a submodel tied to an AI Object " << id << endl;
394         setParentNode(id);
395     }
396
397     //cout << "Submodel: setting IC "<< name << endl;
398     //cout << "heading " << IC.azimuth << endl ;
399     //cout << "speed down " << IC.speed_down_fps << endl ;
400     //cout << "speed east " << IC.speed_east_fps << endl ;
401     //cout << "speed north " << IC.speed_north_fps << endl ;
402     //cout << "parent speed fps in " << IC.speed << "sm speed in " << sm->speed << endl ;
403     //cout << "lat " << IC.lat;
404     //cout << "alt " << IC.alt <<  endl ;
405
406
407     // Set the Initial Conditions that are common to all types of parent
408     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
409     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
410
411 //cout << "wind e " << IC.wind_from_east << " n " << IC.wind_from_north << endl;
412
413     userpos.setLatitudeDeg(IC.lat);
414     userpos.setLongitudeDeg(IC.lon);
415     userpos.setElevationFt(IC.alt);
416
417     _x_offset = sm->x_offset;
418     _y_offset = sm->y_offset;
419     _z_offset = sm->z_offset;
420
421     setOffsetPos();
422
423     //IC.elevation += sm->pitch_offset;
424     //IC.azimuth   += sm->yaw_offset ;
425
426     // pre-process the trig functions
427     cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS);
428     sinRx = sin(-IC.roll * SG_DEGREES_TO_RADIANS);
429     cosRy = cos(-IC.elevation * SG_DEGREES_TO_RADIANS);
430     sinRy = sin(-IC.elevation * SG_DEGREES_TO_RADIANS);
431     cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS);
432     sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS);
433
434
435     // Get submodel initial velocity vector angles in XZ and XY planes.
436     // This vector should be added to aircraft's vector.
437     IC.elevation += (sm->yaw_offset * sinRx) + (sm->pitch_offset * cosRx);
438     IC.azimuth   += (sm->yaw_offset * cosRx) - (sm->pitch_offset * sinRx);
439
440     // calculate the total speed north
441     IC.total_speed_north = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
442             * cos(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_north_fps;
443
444     // calculate the total speed east
445     IC.total_speed_east = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
446             * sin(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_east_fps;
447
448     // calculate the total speed down
449     IC.total_speed_down = sm->speed * -sin(IC.elevation * SG_DEGREES_TO_RADIANS)
450             + IC.speed_down_fps;
451
452     // re-calculate speed, elevation and azimuth
453     IC.speed = sqrt(IC.total_speed_north * IC.total_speed_north
454             + IC.total_speed_east * IC.total_speed_east
455             + IC.total_speed_down * IC.total_speed_down);
456
457     // if speeds are low this calculation can become unreliable
458     if (IC.speed > 1) {
459         IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES;
460         //        cout << "azimuth1 " << IC.azimuth<<endl;
461
462         // rationalise the output
463         if (IC.azimuth < 0)
464             IC.azimuth += 360;
465         else if (IC.azimuth >= 360)
466             IC.azimuth -= 360;
467         // cout << "azimuth2 " << IC.azimuth<<endl;
468
469         IC.elevation = -atan(IC.total_speed_down / sqrt(IC.total_speed_north
470             * IC.total_speed_north + IC.total_speed_east * IC.total_speed_east))
471             * SG_RADIANS_TO_DEGREES;
472     }
473     //cout << "IC.speed " << IC.speed / SG_KT_TO_FPS << endl;
474 }
475
476 void FGSubmodelMgr::updatelat(double lat)
477 {
478     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
479     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
480 }
481
482 void FGSubmodelMgr::loadAI()
483 {
484     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading AI submodels ");
485
486     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
487
488     if (sm_list.empty()) {
489         SG_LOG(SG_AI, SG_ALERT, "Submodels: Unable to read AI submodel list");
490         return;
491     }
492
493     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin(),
494       end = sm_list.end();
495
496     while (sm_list_itr != end) {
497         string path = (*sm_list_itr)->_getSMPath();
498
499         if (path.empty()) {
500             ++sm_list_itr;
501             continue;
502         }
503
504         int id = (*sm_list_itr)->getID();
505         bool serviceable = (*sm_list_itr)->_getServiceable();
506
507         //string type = (*sm_list_itr)->getTypeString();
508         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
509
510         setData(id, path, serviceable);
511         ++sm_list_itr;
512     }
513 }
514
515
516
517 void FGSubmodelMgr::setData(int id, const string& path, bool serviceable)
518 {
519     SGPropertyNode root;
520
521     SGPath config = globals->resolve_aircraft_path(path);
522     try {
523         SG_LOG(SG_AI, SG_DEBUG,
524                 "Submodels: Trying to read AI submodels file: " << config.str());
525         readProperties(config.str(), &root);
526     } catch (const sg_exception &) {
527         SG_LOG(SG_AI, SG_ALERT,
528                 "Submodels: Unable to read AI submodels file: " << config.str());
529         return;
530     }
531
532     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
533     vector<SGPropertyNode_ptr>::iterator it = children.begin();
534     vector<SGPropertyNode_ptr>::iterator end = children.end();
535
536     for (int i = 0; it != end; ++it, i++) {
537         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
538         submodel* sm = new submodel;
539         SGPropertyNode * entry_node = *it;
540         sm->name            = entry_node->getStringValue("name", "none_defined");
541         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
542         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
543         sm->repeat          = entry_node->getBoolValue("repeat", false);
544         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
545         sm->count           = entry_node->getIntValue("count", 1);
546         sm->slaved          = entry_node->getBoolValue("slaved", false);
547         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
548         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
549         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
550         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
551         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
552         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
553         sm->life            = entry_node->getDoubleValue("life", 900.0);
554         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
555         sm->wind            = entry_node->getBoolValue("wind", false);
556         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
557         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
558         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
559         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
560         sm->collision       = entry_node->getBoolValue("collision", false);
561         sm->expiry                      = entry_node->getBoolValue("expiry", false);
562         sm->impact          = entry_node->getBoolValue("impact", false);
563         sm->impact_report   = entry_node->getStringValue("impact-reports");
564         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
565         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
566         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
567         sm->submodel        = entry_node->getStringValue("submodel-path", "");
568         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
569         sm->ext_force       = entry_node->getBoolValue("external-force", false);
570         sm->force_path      = entry_node->getStringValue("force-path", "");
571         sm->random                      = entry_node->getBoolValue("random", false);
572         sm->randomness          = entry_node->getDoubleValue("randomness", 0.5);
573
574         if (sm->contents_node != 0)
575             sm->contents = sm->contents_node->getDoubleValue();
576
577         const char *trigger_path = entry_node->getStringValue("trigger", 0);
578         if (trigger_path) {
579             sm->trigger_node = fgGetNode(trigger_path, true);
580             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
581         } else {
582             sm->trigger_node = 0;
583         }
584
585         if (sm->speed_node != 0)
586             sm->speed = sm->speed_node->getDoubleValue();
587
588         sm->timer = sm->delay;
589         sm->id = id;
590         sm->first_time = false;
591         sm->serviceable = serviceable;
592         sm->sub_id = 0;
593
594         sm->prop = fgGetNode("/ai/submodels/submodel", index, true);
595         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
596         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
597         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
598         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
599         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
600         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
601         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
602         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
603         const string& name = sm->name;
604         sm->prop->setStringValue("name", name.c_str());
605
606         const string& submodel = sm->submodel;
607         sm->prop->setStringValue("submodel", submodel.c_str());
608
609         const string& force_path = sm->force_path;
610         sm->prop->setStringValue("force_path", force_path.c_str());
611         //cout << "set force_path Sub " << force_path << endl;
612
613         if (sm->contents_node != 0)
614             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
615
616         index++;
617         submodels.push_back(sm);
618     }
619 }
620
621 void FGSubmodelMgr::setSubData(int id, const string& path, bool serviceable)
622 {
623     SGPropertyNode root;
624     SGPath config = globals->resolve_aircraft_path(path);
625
626     try {
627         SG_LOG(SG_AI, SG_DEBUG,
628                 "Submodels: Trying to read AI submodels file: " << config.str());
629         readProperties(config.str(), &root);
630
631     } catch (const sg_exception &) {
632         SG_LOG(SG_AI, SG_ALERT,
633                 "Submodels: Unable to read AI submodels file: " << config.str());
634         return;
635     }
636
637     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
638     vector<SGPropertyNode_ptr>::iterator it = children.begin();
639     vector<SGPropertyNode_ptr>::iterator end = children.end();
640
641     for (int i = 0; it != end; ++it, i++) {
642         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
643         submodel* sm = new submodel;
644         SGPropertyNode * entry_node = *it;
645         sm->name            = entry_node->getStringValue("name", "none_defined");
646         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
647         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
648         sm->repeat          = entry_node->getBoolValue("repeat", false);
649         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
650         sm->count           = entry_node->getIntValue("count", 1);
651         sm->slaved          = entry_node->getBoolValue("slaved", false);
652         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
653         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
654         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
655         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
656         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
657         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
658         sm->life            = entry_node->getDoubleValue("life", 900.0);
659         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
660         sm->wind            = entry_node->getBoolValue("wind", false);
661         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
662         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
663         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
664         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
665         sm->collision       = entry_node->getBoolValue("collision", false);
666         sm->expiry          = entry_node->getBoolValue("expiry", false);
667         sm->impact          = entry_node->getBoolValue("impact", false);
668         sm->impact_report   = entry_node->getStringValue("impact-reports");
669         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
670         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
671         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
672         sm->submodel        = entry_node->getStringValue("submodel-path", "");
673         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
674         sm->ext_force       = entry_node->getBoolValue("external-force", false);
675         sm->force_path      = entry_node->getStringValue("force-path", "");
676         sm->random          = entry_node->getBoolValue("random", false);
677         sm->randomness      = entry_node->getDoubleValue("randomness", 0.5);
678
679         if (sm->contents_node != 0)
680             sm->contents = sm->contents_node->getDoubleValue();
681
682         const char *trigger_path = entry_node->getStringValue("trigger", 0);
683         if (trigger_path) {
684             sm->trigger_node = fgGetNode(trigger_path, true);
685             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
686         } else {
687             sm->trigger_node = 0;
688         }
689
690         if (sm->speed_node != 0)
691             sm->speed = sm->speed_node->getDoubleValue();
692
693         sm->timer = sm->delay;
694         sm->id = index;
695         sm->first_time = false;
696         sm->serviceable = serviceable;
697         sm->sub_id = 0;
698
699         sm->prop = fgGetNode("/ai/submodels/subsubmodel", index, true);
700         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
701         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
702         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
703         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
704         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
705         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
706         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
707
708         const string& name = sm->name;
709         sm->prop->setStringValue("name", name.c_str());
710
711         const string& submodel = sm->submodel;
712         sm->prop->setStringValue("submodel-path", submodel.c_str());
713         // cout << " set submodel path AI" << submodel<< endl;
714
715         const string& force_path = sm->force_path;
716         sm->prop->setStringValue("force_path", force_path.c_str());
717         //cout << "set force_path  AI" << force_path << endl;
718
719         if (sm->contents_node != 0)
720             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
721
722         index++;
723         subsubmodels.push_back(sm);
724     }
725 }
726
727 void FGSubmodelMgr::loadSubmodels()
728 {
729     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading sub submodels");
730
731     _found_sub = false;
732
733     submodel_iterator = submodels.begin();
734
735     while (submodel_iterator != submodels.end()) {
736         const string& submodel  = (*submodel_iterator)->submodel;
737         if (!submodel.empty()) {
738             //int id = (*submodel_iterator)->id;
739             bool serviceable = true;
740             SG_LOG(SG_AI, SG_DEBUG, "found path sub sub "
741                     << submodel
742                     << " index " << index
743                     << " name " << (*submodel_iterator)->name);
744
745             if ((*submodel_iterator)->sub_id == 0){
746                 (*submodel_iterator)->sub_id = index;
747                 _found_sub = true;
748                 setSubData(index, submodel, serviceable);
749             }
750         }
751
752         ++submodel_iterator;
753     } // end while
754
755     subsubmodel_iterator = subsubmodels.begin();
756
757     while (subsubmodel_iterator != subsubmodels.end()) {
758
759         submodels.push_back(*subsubmodel_iterator);
760         ++subsubmodel_iterator;
761     } // end while
762
763     subsubmodels.clear();
764
765     //submodel_iterator = submodels.begin();
766
767     //int subcount = 0;
768
769     //while (submodel_iterator != submodels.end()) {
770     //    int id = (*submodel_iterator)->id;
771     //    subcount++;
772
773     //    SG_LOG(SG_AI, SG_ALERT,"after pushback "
774     //            << " parent id " << id
775     //            << " name " << (*submodel_iterator)->name
776     //            << " sub id " << (*submodel_iterator)->sub_id
777     //            << " subcount "<< subcount);
778
779     //    ++submodel_iterator;
780     //}
781 }
782
783 SGVec3d FGSubmodelMgr::getCartOffsetPos() const{
784
785     // convert geodetic positions to geocentered
786     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
787     // Transform to the right coordinate frame, configuration is done in
788     // the x-forward, y-right, z-up coordinates (feet), computation
789     // in the simulation usual body x-forward, y-right, z-down coordinates
790     // (meters) )
791
792     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
793         _y_offset * SG_FEET_TO_METER,
794         -_z_offset * SG_FEET_TO_METER);
795
796     // Transform the user position to the horizontal local coordinate system.
797     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
798
799     // and postrotate the orientation of the user model wrt the horizontal
800     // local frame
801     hlTrans *= SGQuatd::fromYawPitchRollDeg(
802        IC.azimuth,            
803        IC.elevation,
804        IC.roll);
805
806     // The offset converted to the usual body fixed coordinate system
807     // rotated to the earth-fixed coordinates axis
808     SGVec3d off = hlTrans.backTransform(_off);
809
810     // Add the position offset of the user model to get the geocentered position
811     SGVec3d offsetPos = cartuserPos + off;
812     return offsetPos;
813 }
814
815 void FGSubmodelMgr::setOffsetPos(){
816     // convert the offset geocentered position to geodetic
817     SGVec3d cartoffsetPos = getCartOffsetPos();
818
819     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
820
821     //cout << "OFFSET POS" << offsetpos.getElevationFt();
822
823 }
824
825 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
826 {
827     return; // this isn't working atm
828
829     const char* _model_added = _model_added_node->getStringValue();
830
831     std::basic_string <char>::size_type indexCh2b;
832
833     string str2 = _model_added;
834     const char *cstr2b = "multiplayer";
835     indexCh2b = str2.find( cstr2b, 0 );
836
837     if (indexCh2b != string::npos ){        // we will ignore Ballistic Objects - there are potentially too many 
838
839         //cout << "Submodels: model added - " << str2 <<" read path "<< endl;
840         //return;
841         SGPropertyNode *a_node = fgGetNode(_model_added, true);
842         SGPropertyNode *sub_node = a_node->getChild("sim", 0, true);
843         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
844         SGPropertyNode_ptr callsign_node = a_node->getChild("callsign", 0, true);
845
846         //const string& callsign = callsign_node->getStringValue();
847         //cout << "Submodels: model added - " << callsign <<" read callsign "<< endl;
848             return;
849
850         } else {
851             cout << "model added - " << str2 <<" returning "<< endl;
852         return;
853         }
854
855 }
856
857 void FGSubmodelMgr::setParentNode(int id) {
858
859     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
860
861     for (int i = ai->nChildren() - 1; i >= -1; i--) {
862         SGPropertyNode_ptr model;
863
864         if (i < 0) { // last iteration: selected model
865             model = _selected_ac;
866         } else {
867             model = ai->getChild(i);
868             //const string& path = ai->getPath();
869             //const string& name = model->getStringValue("name");
870             int parent_id = model->getIntValue("id");
871             if (!model->nChildren()){
872                 continue;
873             }
874             if (parent_id == id) {
875                 _selected_ac = model;  // save selected model for last iteration
876                 break;
877             }
878
879         }
880         if (!model)
881             continue;
882
883     }// end for loop 
884
885     if (_selected_ac != 0){
886
887         //cout << " parent node found"<< endl;
888
889         const string name  = _selected_ac->getStringValue("name");
890         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
891         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
892         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
893         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
894         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
895         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
896         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
897         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
898         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
899         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
900
901         //cout << name << " IC.speed " << IC.speed << endl;
902
903     } else {
904         SG_LOG(SG_AI, SG_ALERT, "AISubmodel: parent node not found ");
905     }
906
907 }
908 // end of submodel.cxx