]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
Small refactoring of Torsten's refactoring
[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->get_value());
306     ballist->setYawoffset(sm->yaw_offset->get_value());
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     double yaw_offset = sm->yaw_offset->get_value();
357     double pitch_offset = sm->pitch_offset->get_value();
358
359     //cout << " name " << name << " id " << id << " sub id" << sub_id << endl;
360
361     // set the Initial Conditions for the types of submodel parent 
362
363     if (_impact || _hit || _expiry) {
364         // set the data for a submodel tied to a submodel
365
366         _count++;
367
368         IC.lat             = _parent_lat;
369         IC.lon             = _parent_lon;
370         IC.alt             = _parent_elev;
371         IC.roll            = _parent_roll;    // rotation about x axis
372         IC.elevation       = _parent_pitch;   // rotation about y axis
373         IC.azimuth         = _parent_hdg;     // rotation about z axis
374         IC.speed           = _parent_speed;
375         IC.speed_down_fps  = 0;
376         IC.speed_east_fps  = 0;
377         IC.speed_north_fps = 0;
378
379     } else if (id == 0) {
380         //set the data for a submodel tied to the main model
381
382         IC.lat             = _user_lat_node->getDoubleValue();
383         IC.lon             = _user_lon_node->getDoubleValue();
384         IC.alt             = _user_alt_node->getDoubleValue();
385         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
386         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
387         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
388         IC.speed           = _user_speed_node->getDoubleValue();
389         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
390         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
391         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
392
393     } else {
394         // set the data for a submodel tied to an AI Object
395         //cout << " set the data for a submodel tied to an AI Object " << id << endl;
396         setParentNode(id);
397     }
398
399     //cout << "Submodel: setting IC "<< name << endl;
400     //cout << "heading " << IC.azimuth << endl ;
401     //cout << "speed down " << IC.speed_down_fps << endl ;
402     //cout << "speed east " << IC.speed_east_fps << endl ;
403     //cout << "speed north " << IC.speed_north_fps << endl ;
404     //cout << "parent speed fps in " << IC.speed << "sm speed in " << sm->speed << endl ;
405     //cout << "lat " << IC.lat;
406     //cout << "alt " << IC.alt <<  endl ;
407
408
409     // Set the Initial Conditions that are common to all types of parent
410     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
411     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
412
413 //cout << "wind e " << IC.wind_from_east << " n " << IC.wind_from_north << endl;
414
415     userpos.setLatitudeDeg(IC.lat);
416     userpos.setLongitudeDeg(IC.lon);
417     userpos.setElevationFt(IC.alt);
418
419     _x_offset = sm->x_offset;
420     _y_offset = sm->y_offset;
421     _z_offset = sm->z_offset;
422
423     setOffsetPos();
424
425     //IC.elevation += sm->pitch_offset;
426     //IC.azimuth   += sm->yaw_offset ;
427
428     // pre-process the trig functions
429     cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS);
430     sinRx = sin(-IC.roll * SG_DEGREES_TO_RADIANS);
431     cosRy = cos(-IC.elevation * SG_DEGREES_TO_RADIANS);
432     sinRy = sin(-IC.elevation * SG_DEGREES_TO_RADIANS);
433     cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS);
434     sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS);
435
436
437     // Get submodel initial velocity vector angles in XZ and XY planes.
438     // This vector should be added to aircraft's vector.
439     IC.elevation += (yaw_offset * sinRx) + (pitch_offset * cosRx);
440     IC.azimuth   += (yaw_offset * cosRx) - (pitch_offset * sinRx);
441
442     // calculate the total speed north
443     IC.total_speed_north = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
444             * cos(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_north_fps;
445
446     // calculate the total speed east
447     IC.total_speed_east = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
448             * sin(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_east_fps;
449
450     // calculate the total speed down
451     IC.total_speed_down = sm->speed * -sin(IC.elevation * SG_DEGREES_TO_RADIANS)
452             + IC.speed_down_fps;
453
454     // re-calculate speed, elevation and azimuth
455     IC.speed = sqrt(IC.total_speed_north * IC.total_speed_north
456             + IC.total_speed_east * IC.total_speed_east
457             + IC.total_speed_down * IC.total_speed_down);
458
459     // if speeds are low this calculation can become unreliable
460     if (IC.speed > 1) {
461         IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES;
462         //        cout << "azimuth1 " << IC.azimuth<<endl;
463
464         // rationalise the output
465         if (IC.azimuth < 0)
466             IC.azimuth += 360;
467         else if (IC.azimuth >= 360)
468             IC.azimuth -= 360;
469         // cout << "azimuth2 " << IC.azimuth<<endl;
470
471         IC.elevation = -atan(IC.total_speed_down / sqrt(IC.total_speed_north
472             * IC.total_speed_north + IC.total_speed_east * IC.total_speed_east))
473             * SG_RADIANS_TO_DEGREES;
474     }
475     //cout << "IC.speed " << IC.speed / SG_KT_TO_FPS << endl;
476 }
477
478 void FGSubmodelMgr::updatelat(double lat)
479 {
480     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
481     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
482 }
483
484 void FGSubmodelMgr::loadAI()
485 {
486     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading AI submodels ");
487
488     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
489
490     if (sm_list.empty()) {
491         SG_LOG(SG_AI, SG_ALERT, "Submodels: Unable to read AI submodel list");
492         return;
493     }
494
495     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin(),
496       end = sm_list.end();
497
498     while (sm_list_itr != end) {
499         string path = (*sm_list_itr)->_getSMPath();
500
501         if (path.empty()) {
502             ++sm_list_itr;
503             continue;
504         }
505
506         int id = (*sm_list_itr)->getID();
507         bool serviceable = (*sm_list_itr)->_getServiceable();
508
509         //string type = (*sm_list_itr)->getTypeString();
510         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
511
512         setData(id, path, serviceable);
513         ++sm_list_itr;
514     }
515 }
516
517
518
519 void FGSubmodelMgr::setData(int id, const string& path, bool serviceable)
520 {
521     SGPropertyNode root;
522
523     SGPath config = globals->resolve_aircraft_path(path);
524     try {
525         SG_LOG(SG_AI, SG_DEBUG,
526                 "Submodels: Trying to read AI submodels file: " << config.str());
527         readProperties(config.str(), &root);
528     } catch (const sg_exception &) {
529         SG_LOG(SG_AI, SG_ALERT,
530                 "Submodels: Unable to read AI submodels file: " << config.str());
531         return;
532     }
533
534     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
535     vector<SGPropertyNode_ptr>::iterator it = children.begin();
536     vector<SGPropertyNode_ptr>::iterator end = children.end();
537
538     for (int i = 0; it != end; ++it, i++) {
539         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
540         submodel* sm = new submodel;
541         SGPropertyNode * entry_node = *it;
542         sm->name            = entry_node->getStringValue("name", "none_defined");
543         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
544         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
545         sm->repeat          = entry_node->getBoolValue("repeat", false);
546         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
547         sm->count           = entry_node->getIntValue("count", 1);
548         sm->slaved          = entry_node->getBoolValue("slaved", false);
549         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
550         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
551         sm->z_offset        = entry_node->getDoubleValue("z-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         SGPropertyNode_ptr prop_root = fgGetNode("/", true);
575         SGPropertyNode n;
576
577         SGPropertyNode_ptr a = entry_node->getNode("yaw-offset");
578         sm->yaw_offset    = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
579
580         a = entry_node->getNode("pitch-offset");
581         sm->pitch_offset  = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
582
583         if (sm->contents_node != 0)
584             sm->contents = sm->contents_node->getDoubleValue();
585
586         const char *trigger_path = entry_node->getStringValue("trigger", 0);
587         if (trigger_path) {
588             sm->trigger_node = fgGetNode(trigger_path, true);
589             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
590         } else {
591             sm->trigger_node = 0;
592         }
593
594         if (sm->speed_node != 0)
595             sm->speed = sm->speed_node->getDoubleValue();
596
597         sm->timer = sm->delay;
598         sm->id = id;
599         sm->first_time = false;
600         sm->serviceable = serviceable;
601         sm->sub_id = 0;
602
603         sm->prop = fgGetNode("/ai/submodels/submodel", index, true);
604         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
605         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
606         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
607         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
608         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
609         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
610         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
611         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
612         const string& name = sm->name;
613         sm->prop->setStringValue("name", name.c_str());
614
615         const string& submodel = sm->submodel;
616         sm->prop->setStringValue("submodel", submodel.c_str());
617
618         const string& force_path = sm->force_path;
619         sm->prop->setStringValue("force_path", force_path.c_str());
620         //cout << "set force_path Sub " << force_path << endl;
621
622         if (sm->contents_node != 0)
623             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
624
625         index++;
626         submodels.push_back(sm);
627     }
628 }
629
630 void FGSubmodelMgr::setSubData(int id, const string& path, bool serviceable)
631 {
632     SGPropertyNode root;
633     SGPath config = globals->resolve_aircraft_path(path);
634
635     try {
636         SG_LOG(SG_AI, SG_DEBUG,
637                 "Submodels: Trying to read AI submodels file: " << config.str());
638         readProperties(config.str(), &root);
639
640     } catch (const sg_exception &) {
641         SG_LOG(SG_AI, SG_ALERT,
642                 "Submodels: Unable to read AI submodels file: " << config.str());
643         return;
644     }
645
646     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
647     vector<SGPropertyNode_ptr>::iterator it = children.begin();
648     vector<SGPropertyNode_ptr>::iterator end = children.end();
649
650     for (int i = 0; it != end; ++it, i++) {
651         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
652         submodel* sm = new submodel;
653         SGPropertyNode * entry_node = *it;
654         sm->name            = entry_node->getStringValue("name", "none_defined");
655         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
656         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
657         sm->repeat          = entry_node->getBoolValue("repeat", false);
658         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
659         sm->count           = entry_node->getIntValue("count", 1);
660         sm->slaved          = entry_node->getBoolValue("slaved", false);
661         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
662         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
663         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
664         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
665         sm->life            = entry_node->getDoubleValue("life", 900.0);
666         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
667         sm->wind            = entry_node->getBoolValue("wind", false);
668         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
669         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
670         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
671         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
672         sm->collision       = entry_node->getBoolValue("collision", false);
673         sm->expiry          = entry_node->getBoolValue("expiry", false);
674         sm->impact          = entry_node->getBoolValue("impact", false);
675         sm->impact_report   = entry_node->getStringValue("impact-reports");
676         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
677         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
678         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
679         sm->submodel        = entry_node->getStringValue("submodel-path", "");
680         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
681         sm->ext_force       = entry_node->getBoolValue("external-force", false);
682         sm->force_path      = entry_node->getStringValue("force-path", "");
683         sm->random          = entry_node->getBoolValue("random", false);
684         sm->randomness      = entry_node->getDoubleValue("randomness", 0.5);
685
686         SGPropertyNode_ptr prop_root = fgGetNode("/", true);
687         SGPropertyNode n;
688
689         SGPropertyNode_ptr a = entry_node->getNode("yaw-offset");
690         sm->yaw_offset    = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
691
692         a = entry_node->getNode("pitch-offset");
693         sm->pitch_offset  = new FGXMLAutopilot::InputValue(*prop_root, a ? *a : n );
694
695         if (sm->contents_node != 0)
696             sm->contents = sm->contents_node->getDoubleValue();
697
698         const char *trigger_path = entry_node->getStringValue("trigger", 0);
699         if (trigger_path) {
700             sm->trigger_node = fgGetNode(trigger_path, true);
701             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
702         } else {
703             sm->trigger_node = 0;
704         }
705
706         if (sm->speed_node != 0)
707             sm->speed = sm->speed_node->getDoubleValue();
708
709         sm->timer = sm->delay;
710         sm->id = index;
711         sm->first_time = false;
712         sm->serviceable = serviceable;
713         sm->sub_id = 0;
714
715         sm->prop = fgGetNode("/ai/submodels/subsubmodel", index, true);
716         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
717         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
718         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
719         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
720         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
721         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
722         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
723
724         const string& name = sm->name;
725         sm->prop->setStringValue("name", name.c_str());
726
727         const string& submodel = sm->submodel;
728         sm->prop->setStringValue("submodel-path", submodel.c_str());
729         // cout << " set submodel path AI" << submodel<< endl;
730
731         const string& force_path = sm->force_path;
732         sm->prop->setStringValue("force_path", force_path.c_str());
733         //cout << "set force_path  AI" << force_path << endl;
734
735         if (sm->contents_node != 0)
736             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
737
738         index++;
739         subsubmodels.push_back(sm);
740     }
741 }
742
743 void FGSubmodelMgr::loadSubmodels()
744 {
745     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading sub submodels");
746
747     _found_sub = false;
748
749     submodel_iterator = submodels.begin();
750
751     while (submodel_iterator != submodels.end()) {
752         const string& submodel  = (*submodel_iterator)->submodel;
753         if (!submodel.empty()) {
754             //int id = (*submodel_iterator)->id;
755             bool serviceable = true;
756             SG_LOG(SG_AI, SG_DEBUG, "found path sub sub "
757                     << submodel
758                     << " index " << index
759                     << " name " << (*submodel_iterator)->name);
760
761             if ((*submodel_iterator)->sub_id == 0){
762                 (*submodel_iterator)->sub_id = index;
763                 _found_sub = true;
764                 setSubData(index, submodel, serviceable);
765             }
766         }
767
768         ++submodel_iterator;
769     } // end while
770
771     subsubmodel_iterator = subsubmodels.begin();
772
773     while (subsubmodel_iterator != subsubmodels.end()) {
774
775         submodels.push_back(*subsubmodel_iterator);
776         ++subsubmodel_iterator;
777     } // end while
778
779     subsubmodels.clear();
780
781     //submodel_iterator = submodels.begin();
782
783     //int subcount = 0;
784
785     //while (submodel_iterator != submodels.end()) {
786     //    int id = (*submodel_iterator)->id;
787     //    subcount++;
788
789     //    SG_LOG(SG_AI, SG_ALERT,"after pushback "
790     //            << " parent id " << id
791     //            << " name " << (*submodel_iterator)->name
792     //            << " sub id " << (*submodel_iterator)->sub_id
793     //            << " subcount "<< subcount);
794
795     //    ++submodel_iterator;
796     //}
797 }
798
799 SGVec3d FGSubmodelMgr::getCartOffsetPos() const{
800
801     // convert geodetic positions to geocentered
802     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
803     // Transform to the right coordinate frame, configuration is done in
804     // the x-forward, y-right, z-up coordinates (feet), computation
805     // in the simulation usual body x-forward, y-right, z-down coordinates
806     // (meters) )
807
808     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
809         _y_offset * SG_FEET_TO_METER,
810         -_z_offset * SG_FEET_TO_METER);
811
812     // Transform the user position to the horizontal local coordinate system.
813     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
814
815     // and postrotate the orientation of the user model wrt the horizontal
816     // local frame
817     hlTrans *= SGQuatd::fromYawPitchRollDeg(
818        IC.azimuth,            
819        IC.elevation,
820        IC.roll);
821
822     // The offset converted to the usual body fixed coordinate system
823     // rotated to the earth-fixed coordinates axis
824     SGVec3d off = hlTrans.backTransform(_off);
825
826     // Add the position offset of the user model to get the geocentered position
827     SGVec3d offsetPos = cartuserPos + off;
828     return offsetPos;
829 }
830
831 void FGSubmodelMgr::setOffsetPos(){
832     // convert the offset geocentered position to geodetic
833     SGVec3d cartoffsetPos = getCartOffsetPos();
834
835     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
836
837     //cout << "OFFSET POS" << offsetpos.getElevationFt();
838
839 }
840
841 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
842 {
843     return; // this isn't working atm
844
845     const char* _model_added = _model_added_node->getStringValue();
846
847     std::basic_string <char>::size_type indexCh2b;
848
849     string str2 = _model_added;
850     const char *cstr2b = "multiplayer";
851     indexCh2b = str2.find( cstr2b, 0 );
852
853     if (indexCh2b != string::npos ){        // we will ignore Ballistic Objects - there are potentially too many 
854
855         //cout << "Submodels: model added - " << str2 <<" read path "<< endl;
856         //return;
857         SGPropertyNode *a_node = fgGetNode(_model_added, true);
858         SGPropertyNode *sub_node = a_node->getChild("sim", 0, true);
859         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
860         SGPropertyNode_ptr callsign_node = a_node->getChild("callsign", 0, true);
861
862         //const string& callsign = callsign_node->getStringValue();
863         //cout << "Submodels: model added - " << callsign <<" read callsign "<< endl;
864             return;
865
866         } else {
867             cout << "model added - " << str2 <<" returning "<< endl;
868         return;
869         }
870
871 }
872
873 void FGSubmodelMgr::setParentNode(int id) {
874
875     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
876
877     for (int i = ai->nChildren() - 1; i >= -1; i--) {
878         SGPropertyNode_ptr model;
879
880         if (i < 0) { // last iteration: selected model
881             model = _selected_ac;
882         } else {
883             model = ai->getChild(i);
884             //const string& path = ai->getPath();
885             //const string& name = model->getStringValue("name");
886             int parent_id = model->getIntValue("id");
887             if (!model->nChildren()){
888                 continue;
889             }
890             if (parent_id == id) {
891                 _selected_ac = model;  // save selected model for last iteration
892                 break;
893             }
894
895         }
896         if (!model)
897             continue;
898
899     }// end for loop 
900
901     if (_selected_ac != 0){
902
903         //cout << " parent node found"<< endl;
904
905         const string name  = _selected_ac->getStringValue("name");
906         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
907         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
908         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
909         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
910         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
911         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
912         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
913         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
914         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
915         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
916
917         //cout << name << " IC.speed " << IC.speed << endl;
918
919     } else {
920         SG_LOG(SG_AI, SG_ALERT, "AISubmodel: parent node not found ");
921     }
922
923 }
924 // end of submodel.cxx