]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBallistic.cxx
1ea0e89b51c243f45c29cda0ffa680c16c732bcc
[flightgear.git] / src / AIModel / AIBallistic.cxx
1 // FGAIBallistic - FGAIBase-derived class creates a ballistic object
2 //
3 // Written by David Culp, started November 2003.
4 // - davidculp2@comcast.net
5 //
6 // With major additions by Mathias Froehlich & Vivian Meazza 2004-2008
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include <simgear/math/sg_random.h>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/scene/model/modellib.hxx>
29
30 #include <Scenery/scenery.hxx>
31
32 #include "AIBallistic.hxx"
33
34 #include <Main/util.hxx>
35
36 using namespace simgear;
37
38 const double FGAIBallistic::slugs_to_kgs = 14.5939029372;
39 const double FGAIBallistic::slugs_to_lbs = 32.1740485564;
40
41 FGAIBallistic::FGAIBallistic(object_type ot) :
42 FGAIBase(ot),
43 _height(0.0),
44 _ht_agl_ft(0.0),
45 _azimuth(0.0),
46 _elevation(0.0),
47 _rotation(0.0),
48 _formate_to_ac(false),
49 _aero_stabilised(false),
50 _drag_area(0.007),
51 _life_timer(0.0),
52 _gravity(32.1740485564),
53 _buoyancy(0),
54 _wind(true),
55 _mass(0),
56 _random(false),
57 _load_resistance(0),
58 _solid(false),
59 _force_stabilised(false),
60 _slave_to_ac(false),
61 _slave_load_to_ac(false),
62 _contents_lb(0),
63 _report_collision(false),
64 _report_expiry(false),
65 _report_impact(false),
66 _external_force(false),
67 _impact_report_node(fgGetNode("/ai/models/model-impact", true)),
68 _old_height(0),
69 _elapsed_time(0),
70 hs(0)
71
72 {
73     no_roll = false;
74 }
75
76 FGAIBallistic::~FGAIBallistic() {
77 }
78
79 void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) {
80     if (!scFileNode){
81         return;
82     }
83
84     FGAIBase::readFromScenario(scFileNode);
85
86     //setPath(scFileNode->getStringValue("model", "Models/Geometry/rocket.ac")); 
87     setRandom(scFileNode->getBoolValue("random", false));
88     setAzimuth(scFileNode->getDoubleValue("azimuth", 0.0));
89     setElevation(scFileNode->getDoubleValue("elevation", 0));
90     setDragArea(scFileNode->getDoubleValue("eda", 0.007));
91     setLife(scFileNode->getDoubleValue("life", 900.0));
92     setBuoyancy(scFileNode->getDoubleValue("buoyancy", 0));
93     //setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
94     //setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
95     setWind(scFileNode->getBoolValue("wind", false));
96     setRoll(scFileNode->getDoubleValue("roll", 0.0));
97     setCd(scFileNode->getDoubleValue("cd", 0.029));
98     //setMass(scFileNode->getDoubleValue("mass", 0.007));
99     setWeight(scFileNode->getDoubleValue("weight", 0.25));
100     setStabilisation(scFileNode->getBoolValue("aero-stabilised", false));
101     setNoRoll(scFileNode->getBoolValue("no-roll", false));
102     setImpact(scFileNode->getBoolValue("impact", false));
103     setExpiry(scFileNode->getBoolValue("expiry", false));
104     setCollision(scFileNode->getBoolValue("collision", false));
105     setImpactReportNode(scFileNode->getStringValue("impact-reports"));
106     setName(scFileNode->getStringValue("name", "Rocket"));
107     setFuseRange(scFileNode->getDoubleValue("fuse-range", 0.0));
108     setSMPath(scFileNode->getStringValue("submodel-path", ""));
109     setSubID(scFileNode->getIntValue("SubID", 0));
110     setExternalForce(scFileNode->getBoolValue("external-force", false));
111     setForcePath(scFileNode->getStringValue("force-path", ""));
112     setForceStabilisation(scFileNode->getBoolValue("force-stabilised", false));
113     setXoffset(scFileNode->getDoubleValue("x-offset", 0.0));
114     setYoffset(scFileNode->getDoubleValue("y-offset", 0.0));
115     setZoffset(scFileNode->getDoubleValue("z-offset", 0.0));
116     setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
117     setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
118     setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
119     setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
120     setLoadOffset(scFileNode->getDoubleValue("load-offset", 0.0));
121     setSlaved(scFileNode->getBoolValue("slaved", false));
122     setSlavedLoad(scFileNode->getBoolValue("slaved-load", false));
123     setContentsPath(scFileNode->getStringValue("contents"));
124     setParentName(scFileNode->getStringValue("parent"));
125 }
126
127 bool FGAIBallistic::init(bool search_in_AI_path) {
128     FGAIBase::init(search_in_AI_path);
129
130     _impact_reported = false;
131     _collision_reported = false;
132     _expiry_reported = false;
133
134     _impact_lat = 0;
135     _impact_lon = 0;
136     _impact_elev = 0;
137     _impact_hdg = 0;
138     _impact_pitch = 0;
139     _impact_roll = 0;
140     _impact_speed = 0;
141
142     invisible = false;
143
144     _elapsed_time += (sg_random() * 100);
145
146     props->setStringValue("material/name", "");
147     props->setStringValue("name", _name.c_str());
148     props->setStringValue("submodels/path", _path.c_str());
149
150     if (_slave_to_ac){
151         props->setStringValue("force/path", _force_path.c_str());
152         props->setStringValue("contents/path", _contents_path.c_str());
153     }
154
155     if(_parent != ""){
156         setParentNode();
157     }
158
159     setParentNodes(_selected_ac);
160     //props->setStringValue("vector/path", _vector_path.c_str());
161
162     // start with high value so that animations don't trigger yet
163     _ht_agl_ft = 1e10;
164     hdg = _azimuth;
165     pitch = _elevation;
166     roll = _rotation;
167
168     Transform();
169
170     //cout << _name << " speed init: " << speed << endl;
171
172     return true;
173 }
174
175 void FGAIBallistic::bind() {
176     //    FGAIBase::bind();
177
178     props->tie("sim/time/elapsed-sec",
179         SGRawValueMethods<FGAIBallistic,double>(*this,
180         &FGAIBallistic::_getTime));
181     //props->tie("mass-slug",
182     //    SGRawValueMethods<FGAIBallistic,double>(*this,
183     //    &FGAIBallistic::getMass));
184
185     props->tie("material/solid",
186         SGRawValuePointer<bool>(&_solid));
187     props->tie("altitude-agl-ft",
188         SGRawValuePointer<double>(&_ht_agl_ft));
189     props->tie("controls/slave-to-ac",
190         SGRawValueMethods<FGAIBallistic,bool>
191         (*this, &FGAIBallistic::getSlaved, &FGAIBallistic::setSlaved));
192     props->tie("controls/invisible",
193         SGRawValuePointer<bool>(&invisible));
194
195     if(_external_force || _slave_to_ac){
196         props->tie("controls/force_stabilized",
197             SGRawValuePointer<bool>(&_force_stabilised));
198         props->tie("position/global-x", 
199             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosX, 0));
200         props->tie("position/global-y",
201             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosY, 0));
202         props->tie("position/global-z",
203             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosZ, 0));
204         props->tie("velocities/vertical-speed-fps",
205             SGRawValuePointer<double>(&vs));
206         props->tie("velocities/true-airspeed-kt",
207             SGRawValuePointer<double>(&speed));
208         props->tie("velocities/horizontal-speed-fps",
209             SGRawValuePointer<double>(&hs));
210         props->tie("position/altitude-ft",
211             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getElevationFt, &FGAIBase::_setAltitude));
212         props->tie("position/latitude-deg", 
213             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLatitude, &FGAIBase::_setLatitude));
214         props->tie("position/longitude-deg",
215             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLongitude, &FGAIBase::_setLongitude));
216         props->tie("orientation/hdg-deg",
217             SGRawValuePointer<double>(&hdg));
218         props->tie("orientation/pitch-deg",
219             SGRawValuePointer<double>(&pitch));
220         props->tie("orientation/roll-deg",
221             SGRawValuePointer<double>(&roll));
222         props->tie("controls/slave-load-to-ac",
223             SGRawValueMethods<FGAIBallistic,bool>
224             (*this, &FGAIBallistic::getSlavedLoad, &FGAIBallistic::setSlavedLoad));
225         props->tie("position/load-offset",
226             SGRawValueMethods<FGAIBallistic,double>
227             (*this, &FGAIBallistic::getLoadOffset, &FGAIBallistic::setLoadOffset));
228         props->tie("load/distance-to-hitch-ft",
229             SGRawValueMethods<FGAIBallistic,double>
230             (*this, &FGAIBallistic::getDistanceLoadToHitch));
231         props->tie("load/elevation-to-hitch-deg",
232             SGRawValueMethods<FGAIBallistic,double>
233             (*this, &FGAIBallistic::getElevLoadToHitch));
234         props->tie("load/bearing-to-hitch-deg",
235             SGRawValueMethods<FGAIBallistic,double>
236             (*this, &FGAIBallistic::getBearingLoadToHitch));
237         props->tie("material/load-resistance",
238         SGRawValuePointer<double>(&_load_resistance));
239     }
240
241 }
242
243 void FGAIBallistic::unbind() {
244 //    FGAIBase::unbind();
245
246     props->untie("sim/time/elapsed-sec");
247     props->untie("mass-slug");
248     props->untie("material/solid");
249     props->untie("altitude-agl-ft");
250     props->untie("controls/slave-to-ac");
251     props->untie("controls/invisible");
252
253     if(_external_force || _slave_to_ac){
254         props->untie("position/global-y");
255         props->untie("position/global-x");
256         props->untie("position/global-z");
257         props->untie("velocities/vertical-speed-fps");
258         props->untie("velocities/true-airspeed-kt");
259         props->untie("velocities/horizontal-speed-fps");
260         props->untie("position/altitude-ft");
261         props->untie("position/latitude-deg");
262         props->untie("position/longitude-deg");
263         props->untie("position/ht-agl-ft");
264         props->untie("orientation/hdg-deg");
265         props->untie("orientation/pitch-deg");
266         props->untie("orientation/roll-deg");
267         props->untie("controls/force_stabilized");
268         props->untie("position/load-offset");
269         props->untie("load/distance-to-hitch-ft");
270         props->untie("load/elevation-to-hitch-deg");
271         props->untie("load/bearing-to-hitch-deg");
272         props->untie("material/load-resistance");
273     }
274 }
275
276 void FGAIBallistic::update(double dt) {
277     FGAIBase::update(dt);
278     _setUserPos();
279
280     if (_formate_to_ac){
281         formateToAC(dt);
282         Transform();
283     } else if (_slave_to_ac){
284         slaveToAC(dt);
285         Transform();
286     } else if (!invisible){
287         Run(dt);
288         Transform();
289     }
290
291 }
292
293 void FGAIBallistic::setAzimuth(double az) {
294
295     if (_random)
296         hdg = _azimuth = (az - 5 ) + (10 * sg_random());
297     else 
298         hdg = _azimuth = az;
299
300     //cout << _name << " init hdg " << hdg << " random " << _random << endl;
301 }
302
303 void FGAIBallistic::setElevation(double el) {
304     pitch = _elevation = el;
305 }
306
307 void FGAIBallistic::setRoll(double rl) {
308     roll = _rotation = rl;
309 }
310
311 void FGAIBallistic::setStabilisation(bool val) {
312     _aero_stabilised = val;
313 }
314
315 void FGAIBallistic::setForceStabilisation(bool val) {
316     _force_stabilised = val;
317 }
318
319 void FGAIBallistic::setNoRoll(bool nr) {
320     no_roll = nr;
321 }
322
323 void FGAIBallistic::setDragArea(double a) {
324     _drag_area = a;
325 }
326
327 void FGAIBallistic::setLife(double seconds) {
328
329     if (_random){
330         life = seconds * _randomness + (seconds * (1 -_randomness) * sg_random());
331         //cout << "life " << life << endl;
332     } else
333         life = seconds;
334 }
335
336 void FGAIBallistic::setBuoyancy(double fpss) {
337     _buoyancy = fpss;
338 }
339
340 void FGAIBallistic::setWind_from_east(double fps) {
341     _wind_from_east = fps;
342 }
343
344 void FGAIBallistic::setWind_from_north(double fps) {
345     _wind_from_north = fps;
346 }
347
348 void FGAIBallistic::setWind(bool val) {
349     _wind = val;
350 }
351
352 void FGAIBallistic::setCd(double c) {
353     _Cd = c;
354 }
355
356 void FGAIBallistic::setMass(double m) {
357     _mass = m;
358 }
359
360 void FGAIBallistic::setWeight(double w) {
361     _weight_lb = w;
362 }
363
364 void FGAIBallistic::setRandomness(double r) {
365     _randomness = r;
366 }
367
368 void FGAIBallistic::setRandom(bool r) {
369     _random = r;
370 }
371
372 void FGAIBallistic::setImpact(bool i) {
373     _report_impact = i;
374 }
375
376 void FGAIBallistic::setCollision(bool c) {
377     _report_collision = c;
378 }
379
380 void FGAIBallistic::setExpiry(bool e) {
381     _report_expiry = e;
382 }
383
384 void FGAIBallistic::setExternalForce(bool f) {
385     _external_force = f;
386 }
387
388 void FGAIBallistic::setImpactReportNode(const string& path) {
389
390     if (!path.empty())
391         _impact_report_node = fgGetNode(path.c_str(), true);
392 }
393
394 void FGAIBallistic::setName(const string& n) {
395     _name = n;
396 }
397
398 void FGAIBallistic::setSMPath(const string& s) {
399     _path = s;
400     //cout << "submodel path " << _path << endl;
401 }
402
403 void FGAIBallistic::setFuseRange(double f) {
404     _fuse_range = f;
405 }
406
407 void FGAIBallistic::setSubID(int i) {
408     _subID = i;
409 }
410
411 void FGAIBallistic::setSubmodel(const string& s) {
412     _submodel = s;
413 }
414
415 void FGAIBallistic::setGroundOffset(double g) {
416     _ground_offset = g;
417 }
418
419 void FGAIBallistic::setLoadOffset(double l) {
420     _load_offset = l;
421 }
422
423 double FGAIBallistic::getLoadOffset() const {
424     return _load_offset;
425 }
426
427 void FGAIBallistic::setSlaved(bool s) {
428     _slave_to_ac = s;
429 }
430
431 void FGAIBallistic::setFormate(bool f) {
432     _formate_to_ac = f;
433 }
434
435 void FGAIBallistic::setContentsPath(const string& path) {
436
437     _contents_path = path;
438
439     if (!path.empty()) {
440         _contents_node = fgGetNode(path.c_str(), true);
441     }
442 }
443
444 void FGAIBallistic::setContentsNode(SGPropertyNode_ptr node) {
445
446     if (node != 0) {
447         _contents_node = node;
448         _contents_path = _contents_node->getDisplayName();
449     }
450 }
451
452 void FGAIBallistic::setParentNodes(SGPropertyNode_ptr node) {
453
454     if (node != 0) {
455         _pnode = node;
456         _p_pos_node = _pnode->getChild("position", 0, true);
457         _p_lat_node = _p_pos_node->getChild("latitude-deg", 0, true);
458         _p_lon_node = _p_pos_node->getChild("longitude-deg", 0, true);
459         _p_alt_node = _p_pos_node->getChild("altitude-ft", 0, true);
460
461         _p_ori_node = _pnode->getChild("orientation", 0, true);
462         _p_pch_node = _p_ori_node->getChild("pitch-deg", 0, true);
463         _p_rll_node = _p_ori_node->getChild("roll-deg", 0, true);
464         _p_hdg_node = _p_ori_node->getChild("true-heading-deg",0, true);
465
466         _p_vel_node = _pnode->getChild("velocities", 0, true);
467         _p_spd_node = _p_vel_node->getChild("true-airspeed-kt", 0, true);
468     }
469
470 }
471
472 void FGAIBallistic::setParentPos() {
473
474     if (_pnode != 0) {
475         double lat = _p_lat_node->getDoubleValue();
476         double lon = _p_lon_node->getDoubleValue();
477         double alt = _p_alt_node->getDoubleValue();
478
479         _parentpos.setLongitudeDeg(lon);
480         _parentpos.setLatitudeDeg(lat);
481         _parentpos.setElevationFt(alt);
482     }
483
484 }
485
486 bool FGAIBallistic::getSlaved() const {
487     return _slave_to_ac;
488 }
489
490 bool FGAIBallistic::getFormate() const {
491     return _formate_to_ac;
492 }
493
494 double FGAIBallistic::getMass() const {
495     return _mass;
496 }
497
498 double FGAIBallistic::getContents() {
499     if(_contents_node){
500         _contents_lb = _contents_node->getChild("level-lbs",0,1)->getDoubleValue();
501     }
502     return _contents_lb;
503 }
504
505 void FGAIBallistic::setContents(double c) {
506     if(_contents_node) 
507         _contents_lb = _contents_node->getChild("level-gal_us",0,1)->setDoubleValue(c);
508 }
509
510 void FGAIBallistic::setSlavedLoad(bool l) {
511     _slave_load_to_ac = l;
512 }
513
514 bool FGAIBallistic::getSlavedLoad() const {
515     return _slave_load_to_ac;
516 }
517
518 void FGAIBallistic::setForcePath(const string& p) {
519     _force_path = p;
520     if (!_force_path.empty()) {
521         SGPropertyNode *fnode = fgGetNode(_force_path.c_str(), 0, true );
522         _force_node = fnode->getChild("force-lb", 0, true);
523         _force_azimuth_node = fnode->getChild("force-azimuth-deg", 0, true);
524         _force_elevation_node = fnode->getChild("force-elevation-deg", 0, true);
525     }
526 }
527
528 bool FGAIBallistic::getHtAGL(double start){
529
530     if (getGroundElevationM(SGGeod::fromGeodM(pos, start),
531         _elevation_m, &_material)) {
532             _ht_agl_ft = pos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
533
534             if (_material) {
535                 const vector<string>& names = _material->get_names();
536                 _solid = _material->get_solid();
537                 _load_resistance = _material->get_load_resistance();
538                 _frictionFactor =_material->get_friction_factor();
539
540                 if (!names.empty())
541                     props->setStringValue("material/name", names[0].c_str());
542                 else
543                     props->setStringValue("material/name", "");
544
545                 _mat_name = names[0];
546
547                 //cout << "material " << _mat_name 
548                 //<< " solid " << _solid 
549                 //<< " load " << _load_resistance
550                 //<< " frictionFactor " << _frictionFactor
551                 //<< endl;
552
553             }
554
555             return true;
556     } else {
557         return false;
558     }
559
560 }
561
562 double FGAIBallistic::getRecip(double az){
563     // calculate the reciprocal of the input azimuth 
564     if(az - 180 < 0){
565         return az + 180;
566     } else {
567         return az - 180; 
568     }
569 }
570
571 void FGAIBallistic::setPch(double e, double dt, double coeff){
572     double c = dt / (coeff + dt);
573     pitch = (e * c) + (pitch * (1 - c));
574 }
575
576 void FGAIBallistic::setBnk(double r, double dt, double coeff){
577     double c = dt / (coeff + dt);
578     roll = (r * c) + (roll * (1 - c));
579 }
580
581 void FGAIBallistic::setHt(double h, double dt, double coeff){
582     double c = dt / (coeff + dt);
583     _height = (h * c) + (_height * (1 - c));
584 }
585
586 void FGAIBallistic::setHdg(double az, double dt, double coeff){
587     double recip = getRecip(hdg);
588     double c = dt / (coeff + dt);
589     //we need to ensure that we turn the short way to the new hdg
590     if (az < recip && az < hdg && hdg > 180) {
591         hdg = ((az + 360) * c) + (hdg * (1 - c));
592     } else if (az > recip && az > hdg && hdg <= 180){
593         hdg = ((az - 360) * c) + (hdg * (1 - c));
594     } else {
595         hdg = (az * c) + (hdg * (1 - c));
596     }
597 }
598
599 double  FGAIBallistic::getTgtXOffset() const {
600     return _tgt_x_offset;
601 }
602
603 double  FGAIBallistic::getTgtYOffset() const {
604     return _tgt_y_offset;
605
606
607 double  FGAIBallistic::getTgtZOffset() const {
608     return _tgt_z_offset;
609 }
610
611 void FGAIBallistic::setTgtXOffset(double x){
612     _tgt_x_offset = x;
613 }
614
615 void FGAIBallistic::setTgtYOffset(double y){
616     _tgt_y_offset = y;
617 }
618
619 void FGAIBallistic::setTgtZOffset(double z){
620     _tgt_z_offset = z;
621 }
622
623 void FGAIBallistic::slaveToAC(double dt){
624
625     double hdg, pch, rll = 0;
626
627     if (_pnode != 0) {
628         setParentPos();
629         hdg = _p_hdg_node->getDoubleValue();
630         pch = _p_pch_node->getDoubleValue();
631         rll = _p_rll_node->getDoubleValue();
632         setOffsetPos(_parentpos, hdg, pch, rll);
633         setSpeed(_p_spd_node->getDoubleValue());
634     }else {
635         hdg = manager->get_user_heading();
636         pch = manager->get_user_pitch();
637         rll = manager->get_user_roll();
638         setOffsetPos(userpos, hdg, pch, rll);
639         setSpeed(manager->get_user_speed());
640     }
641
642     pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
643     pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
644     pos.setElevationFt(_offsetpos.getElevationFt());
645     setHeading(hdg);
646     setPitch(pch + _pitch_offset);
647     setBank(rll + _roll_offset);
648     setOffsetVelocity(dt, pos);
649
650     //update the mass (slugs)
651     _mass = (_weight_lb + getContents()) / slugs_to_lbs;
652
653     _impact_reported = false;
654
655     //cout << _name << " _mass "<<_mass <<" " << getContents() 
656     //<< " " << getContents() / slugs_to_lbs << " weight " << _weight_lb << endl;
657     //    cout << _name << " update hs " << hs << " vs " << vs << endl;
658 }
659
660 void FGAIBallistic::Run(double dt) {
661     _life_timer += dt;
662
663     // if life = -1 the object does not die
664     if (_life_timer > life && life != -1){
665
666         if (_report_expiry && !_expiry_reported && !_impact_reported && !_collision_reported){
667             //cout<<"AIBallistic: expiry"<< endl;
668             handle_expiry();
669         } else
670             setDie(true);
671
672     }
673
674     //set the contents in the appropriate tank or other property in the parent to zero
675     setContents(0);
676
677     //randomise Cd by +- 10%
678     if (_random)
679         _Cd = _Cd * 0.90 + (0.10 * sg_random());
680
681     // Adjust Cd by Mach number. The equations are based on curves
682     // for a conventional shell/bullet (no boat-tail).
683     double Cdm;
684
685     if (Mach < 0.7)
686         Cdm = 0.0125 * Mach + _Cd;
687     else if (Mach < 1.2 )
688         Cdm = 0.3742 * pow(Mach, 2) - 0.252 * Mach + 0.0021 + _Cd;
689     else
690         Cdm = 0.2965 * pow(Mach, -1.1506) + _Cd;
691
692     //cout <<_name << " Mach " << Mach << " Cdm " << Cdm 
693     //    << " ballistic speed kts "<< speed <<  endl;
694
695     // drag = Cd * 0.5 * rho * speed * speed * drag_area;
696     // rho is adjusted for altitude in void FGAIBase::update,
697     // using Standard Atmosphere (sealevel temperature 15C)
698     // acceleration = drag/mass;
699     // adjust speed by drag
700     speed -= (Cdm * 0.5 * rho * speed * speed * _drag_area/_mass) * dt;
701
702     // don't let speed become negative
703     if ( speed < 0.0 )
704         speed = 0.0;
705
706     double speed_fps = speed * SG_KT_TO_FPS;
707     //double hs;
708
709     // calculate vertical and horizontal speed components
710     if (speed == 0.0) {
711         hs = vs = 0.0;
712     } else {
713         vs = sin( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
714         hs = cos( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
715     }
716
717     //resolve horizontal speed into north and east components:
718     double speed_north_fps = cos(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
719     double speed_east_fps = sin(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
720
721     // convert horizontal speed (fps) to degrees per second
722     double speed_north_deg_sec = speed_north_fps / ft_per_deg_lat;
723     double speed_east_deg_sec  = speed_east_fps / ft_per_deg_lon;
724
725     // if wind not required, set to zero
726     if (!_wind) {
727         _wind_from_north = 0;
728         _wind_from_east = 0;
729     } else {
730         _wind_from_north = manager->get_wind_from_north();
731         _wind_from_east = manager->get_wind_from_east();
732     }
733
734     //calculate velocity due to external force
735     double force_speed_north_deg_sec = 0;
736     double force_speed_east_deg_sec = 0;
737 //    double vs_force_fps = 0;
738     double hs_force_fps = 0;
739     double v_force_acc_fpss = 0;
740     double force_speed_north_fps = 0;
741     double force_speed_east_fps = 0;
742     double h_force_lbs = 0;
743     double normal_force_lbs = 0;
744     double normal_force_fpss = 0;
745     double static_friction_force_lbs = 0;
746     double dynamic_friction_force_lbs = 0;
747     double friction_force_speed_north_fps = 0;
748     double friction_force_speed_east_fps = 0;
749     double friction_force_speed_north_deg_sec = 0;
750     double friction_force_speed_east_deg_sec = 0;
751     double force_elevation_deg = 0;
752
753     if (_external_force) {
754         //cout << _name << " external force" << endl;
755
756         SGPropertyNode *n = fgGetNode(_force_path.c_str(), true);
757         double force_lbs            = n->getChild("force-lb", 0, true)->getDoubleValue();
758         force_elevation_deg         = n->getChild("force-elevation-deg", 0, true)->getDoubleValue();
759         double force_azimuth_deg    = n->getChild("force-azimuth-deg", 0, true)->getDoubleValue();
760         
761         //resolve force into vertical and horizontal components:
762         double v_force_lbs = force_lbs * sin( force_elevation_deg * SG_DEGREES_TO_RADIANS );
763         h_force_lbs = force_lbs * cos( force_elevation_deg * SG_DEGREES_TO_RADIANS );
764
765         //ground interaction 
766
767         if (getHtAGL(10000)){
768             double deadzone = 0.1;
769
770             if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid){
771                 normal_force_lbs = (_mass * slugs_to_lbs) - v_force_lbs;
772
773                 if ( normal_force_lbs < 0 )
774                     normal_force_lbs = 0;
775
776                 pos.setElevationFt(0 + _ground_offset);
777                 if (vs < 0) 
778                     vs = -vs * 0.5;
779
780                 // calculate friction
781                 // we assume a static Coefficient of Friction (mu) of 0.62 (wood on concrete)
782                 double mu = 0.62;
783
784                 static_friction_force_lbs = mu * normal_force_lbs * _frictionFactor;
785
786                 //adjust horizontal force. We assume that a speed of <= 5 fps is static 
787                 if (h_force_lbs <= static_friction_force_lbs && hs <= 5){
788                     h_force_lbs = hs = 0;
789                     speed_north_fps = speed_east_fps = 0;
790                 } else
791                     dynamic_friction_force_lbs = (static_friction_force_lbs * 0.95);
792
793                 //ignore wind when on the ground for now
794                 //TODO fix this
795                 _wind_from_north = 0;
796                 _wind_from_east = 0;
797
798             }
799
800         }
801
802         //acceleration = (force(lbsf)/mass(slugs))
803         v_force_acc_fpss = v_force_lbs/_mass;
804         normal_force_fpss = normal_force_lbs/_mass;
805         double h_force_acc_fpss = h_force_lbs/_mass;
806         double dynamic_friction_acc_fpss = dynamic_friction_force_lbs/_mass;
807
808         // velocity = acceleration * dt
809         hs_force_fps = h_force_acc_fpss * dt;
810         double friction_force_fps = dynamic_friction_acc_fpss * dt;
811
812         //resolve horizontal speeds into north and east components:
813         force_speed_north_fps   = cos(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
814         force_speed_east_fps    = sin(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
815
816         friction_force_speed_north_fps = cos(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
817         friction_force_speed_east_fps  = sin(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
818
819         // convert horizontal speed (fps) to degrees per second
820         force_speed_north_deg_sec = force_speed_north_fps / ft_per_deg_lat;
821         force_speed_east_deg_sec  = force_speed_east_fps / ft_per_deg_lon;
822
823         friction_force_speed_north_deg_sec = friction_force_speed_north_fps / ft_per_deg_lat;
824         friction_force_speed_east_deg_sec  = friction_force_speed_east_fps / ft_per_deg_lon;
825     }
826
827     // convert wind speed (fps) to degrees lat/lon per second
828     double wind_speed_from_north_deg_sec = _wind_from_north / ft_per_deg_lat;
829     double wind_speed_from_east_deg_sec  = _wind_from_east / ft_per_deg_lon;
830
831     //recombine the horizontal velocity components
832     hs = sqrt(((speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps) 
833         * (speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
834         + ((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps) 
835         * (speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps)));
836
837     if (hs <= 0.00001)
838         hs = 0;
839
840     // adjust vertical speed for acceleration of gravity, buoyancy, and vertical force
841     vs -= (_gravity - _buoyancy - v_force_acc_fpss - normal_force_fpss) * dt;
842
843     if (vs <= 0.00001 && vs >= -0.00001)
844         vs = 0;
845
846     // set new position
847     if(_slave_load_to_ac) {
848         setOffsetPos(pos, 
849             manager->get_user_heading(),
850             manager->get_user_pitch(), 
851             manager->get_user_roll()
852             );
853         pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
854         pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
855         pos.setElevationFt(_offsetpos.getElevationFt());
856
857         if (getHtAGL(10000)){
858             double deadzone = 0.1;
859
860             if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid){
861                 pos.setElevationFt(0 + _ground_offset);
862             } else {
863                 pos.setElevationFt(_offsetpos.getElevationFt() + _load_offset);
864             }
865
866         }
867     } else {
868         pos.setLatitudeDeg( pos.getLatitudeDeg()
869             + (speed_north_deg_sec - wind_speed_from_north_deg_sec 
870             + force_speed_north_deg_sec + friction_force_speed_north_deg_sec) * dt );
871         pos.setLongitudeDeg( pos.getLongitudeDeg()
872             + (speed_east_deg_sec - wind_speed_from_east_deg_sec 
873             + force_speed_east_deg_sec + friction_force_speed_east_deg_sec) * dt );
874         pos.setElevationFt(pos.getElevationFt() + vs * dt);
875     }
876
877 //    cout << _name << " run hs " << hs << " vs " << vs << endl;
878
879     // recalculate total speed
880     if ( vs == 0 && hs == 0)
881         speed = 0;
882     else
883         speed = sqrt( vs * vs + hs * hs) / SG_KT_TO_FPS;
884
885     // recalculate elevation and azimuth (velocity vectors)
886     _elevation = atan2( vs, hs ) * SG_RADIANS_TO_DEGREES;
887     _azimuth =  atan2((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps), 
888         (speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
889         * SG_RADIANS_TO_DEGREES;
890
891     // rationalise azimuth
892     if (_azimuth < 0)
893         _azimuth += 360;
894
895     if (_aero_stabilised) { // we simulate rotational moment of inertia by using a filter
896         //cout<< "_aero_stabilised "<< endl;
897         const double coeff = 0.9;
898
899         // we assume a symetrical MI about the pitch and yaw axis
900         setPch(_elevation, dt, coeff);
901         setHdg(_azimuth, dt, coeff);
902     } else if (_force_stabilised) { // we simulate rotational moment of inertia by using a filter
903         //cout<< "_force_stabilised "<< endl;
904         
905         const double coeff = 0.9;
906         double ratio = h_force_lbs/(_mass * slugs_to_lbs);
907
908         if (ratio >  1) ratio =  1;
909         if (ratio < -1) ratio = -1;
910
911         double force_pitch = acos(ratio) * SG_RADIANS_TO_DEGREES;
912
913         if (force_pitch <= force_elevation_deg)
914             force_pitch = force_elevation_deg;
915
916         // we assume a symetrical MI about the pitch and yaw axis
917         setPch(force_pitch,dt, coeff);
918         setHdg(_azimuth, dt, coeff);
919     }
920
921     //do impacts and collisions
922     if (_report_impact && !_impact_reported)
923         handle_impact();
924
925     if (_report_collision && !_collision_reported)
926         handle_collision();
927
928     // set destruction flag if altitude less than sea level -1000
929     if (altitude_ft < -1000.0 && life != -1)
930         setDie(true);
931
932 }  // end Run
933
934 double FGAIBallistic::_getTime() const {
935     return _life_timer;
936 }
937
938 void FGAIBallistic::handle_impact() {
939
940     // try terrain intersection
941     double start = pos.getElevationM() + 10;
942
943     if(!getHtAGL(start)) 
944         return;
945
946     if (_ht_agl_ft <= 0) {
947         SG_LOG(SG_GENERAL, SG_DEBUG, "AIBallistic: terrain impact");
948         report_impact(_elevation_m);
949         _impact_reported = true;
950
951         if (life == -1){
952             invisible = true;
953         } else if (_subID == 0)  // kill the AIObject if there is no subsubmodel
954             setDie(true);
955     } 
956 }
957
958 void FGAIBallistic::handle_expiry() {
959
960     SG_LOG(SG_GENERAL, SG_DEBUG, "AIBallistic: handle_expiry " << pos.getElevationM());
961
962     report_impact(pos.getElevationM());
963     _expiry_reported = true;
964
965     if (life == -1){
966         invisible = true;
967     } else if (_subID == 0){  // kill the AIObject if there is no subsubmodel
968         setDie(true);
969     }
970
971 }
972
973 void FGAIBallistic::handle_collision()
974 {
975     const FGAIBase *object = manager->calcCollision(pos.getElevationFt(),
976         pos.getLatitudeDeg(),pos.getLongitudeDeg(), _fuse_range);
977
978     if (object) {
979         report_impact(pos.getElevationM(), object);
980         _collision_reported = true;
981     }
982 }
983
984 void FGAIBallistic::report_impact(double elevation, const FGAIBase *object)
985 {
986     _impact_lat    = pos.getLatitudeDeg();
987     _impact_lon    = pos.getLongitudeDeg();
988     _impact_elev   = elevation;
989     _impact_speed  = speed * SG_KT_TO_MPS;
990     _impact_hdg    = hdg;
991     _impact_pitch  = pitch;
992     _impact_roll   = roll;
993
994     SGPropertyNode *n = props->getNode("impact", true);
995
996     if (object)
997         n->setStringValue("type", object->getTypeString());
998     else
999         n->setStringValue("type", "terrain");
1000
1001     SG_LOG(SG_GENERAL, SG_DEBUG, "AIBallistic: object impact" << _name << " lon " <<_impact_lon);
1002
1003     n->setDoubleValue("longitude-deg", _impact_lon);
1004     n->setDoubleValue("latitude-deg", _impact_lat);
1005     n->setDoubleValue("elevation-m", _impact_elev);
1006     n->setDoubleValue("heading-deg", _impact_hdg);
1007     n->setDoubleValue("pitch-deg", _impact_pitch);
1008     n->setDoubleValue("roll-deg", _impact_roll);
1009     n->setDoubleValue("speed-mps", _impact_speed);
1010
1011     _impact_report_node->setStringValue(props->getPath());
1012 }
1013
1014 SGVec3d FGAIBallistic::getCartUserPos() const {
1015     SGVec3d cartUserPos = SGVec3d::fromGeod(userpos);
1016     return cartUserPos;
1017 }
1018
1019 SGVec3d FGAIBallistic::getCartHitchPos() const{
1020
1021     // convert geodetic positions to geocentered
1022     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
1023     //SGVec3d cartPos = getCartPos();
1024
1025     // Transform to the right coordinate frame, configuration is done in
1026     // the x-forward, y-right, z-up coordinates (feet), computation
1027     // in the simulation usual body x-forward, y-right, z-down coordinates
1028     // (meters) )
1029     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1030             _y_offset * SG_FEET_TO_METER,
1031             -_z_offset * SG_FEET_TO_METER);
1032
1033     // Transform the user position to the horizontal local coordinate system.
1034     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
1035
1036     // and postrotate the orientation of the user model wrt the horizontal
1037     // local frame
1038     hlTrans *= SGQuatd::fromYawPitchRollDeg(
1039         manager->get_user_heading(),
1040         manager->get_user_pitch(),
1041         manager->get_user_roll());
1042
1043     // The offset converted to the usual body fixed coordinate system
1044     // rotated to the earth-fixed coordinates axis
1045     SGVec3d off = hlTrans.backTransform(_off);
1046
1047     // Add the position offset of the user model to get the geocentered position
1048     SGVec3d offsetPos = cartuserPos + off;
1049
1050     return offsetPos;
1051 }
1052
1053 void FGAIBallistic::setOffsetPos(SGGeod inpos, double heading, double pitch, double roll){
1054     // convert the hitch geocentered position to geodetic
1055
1056     SGVec3d cartoffsetPos = getCartOffsetPos(inpos, heading, pitch, roll);
1057
1058     //SGVec3d cartoffsetPos = getCartHitchPos();
1059
1060     //SGGeodesy::SGCartToGeod(cartoffsetPos, hitchpos);
1061     SGGeodesy::SGCartToGeod(cartoffsetPos, _offsetpos);
1062
1063 }
1064
1065 double FGAIBallistic::getDistanceLoadToHitch() const {
1066     //calculate the distance load to hitch 
1067     SGVec3d carthitchPos = getCartHitchPos();
1068     SGVec3d cartPos = getCartPos();
1069
1070     SGVec3d diff = carthitchPos - cartPos;
1071     double distance = norm(diff);
1072     return distance * SG_METER_TO_FEET;
1073 }
1074
1075
1076 double FGAIBallistic::getElevLoadToHitch() const {
1077     // now the angle, positive angles are upwards
1078     double distance = getDistanceLoadToHitch() * SG_FEET_TO_METER;
1079     double angle = 0;
1080     double daltM = _offsetpos.getElevationM() - pos.getElevationM();
1081
1082     if (fabs(distance) < SGLimits<float>::min()) {
1083         angle = 0;
1084     } else {
1085         double sAngle = daltM/distance;
1086         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1087         angle = SGMiscd::rad2deg(asin(sAngle));
1088     }
1089
1090     return angle;
1091 }
1092
1093 double FGAIBallistic::getBearingLoadToHitch() const {
1094     //calculate the bearing and range of the second pos from the first
1095     double az1, az2, distance;
1096
1097     geo_inverse_wgs_84(pos, _offsetpos, &az1, &az2, &distance);
1098
1099     return az1;
1100 }
1101
1102 double FGAIBallistic::getRelBrgHitchToUser() const {
1103     //calculate the relative bearing 
1104     double az1, az2, distance;
1105
1106     geo_inverse_wgs_84(_offsetpos, userpos, &az1, &az2, &distance);
1107
1108     double rel_brg = az1 - hdg;
1109
1110     if (rel_brg > 180)
1111         rel_brg -= 360;
1112
1113     return rel_brg;
1114 }
1115
1116 double FGAIBallistic::getElevHitchToUser() const {
1117
1118     //calculate the distance from the user position
1119     SGVec3d carthitchPos = getCartHitchPos();
1120     SGVec3d cartuserPos = getCartUserPos();
1121
1122     SGVec3d diff = cartuserPos - carthitchPos;
1123
1124     double distance = norm(diff);
1125     double angle = 0;
1126
1127     double daltM = userpos.getElevationM() - _offsetpos.getElevationM();
1128
1129     // now the angle, positive angles are upwards
1130     if (fabs(distance) < SGLimits<float>::min()) {
1131         angle = 0;
1132     } else {
1133         double sAngle = daltM/distance;
1134         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1135         angle = SGMiscd::rad2deg(asin(sAngle));
1136     }
1137
1138     return angle;
1139 }
1140
1141 void FGAIBallistic::setTgtOffsets(double dt, double coeff){
1142     double c = dt / (coeff + dt);
1143
1144     _x_offset = (_tgt_x_offset * c) + (_x_offset * (1 - c));
1145     _y_offset = (_tgt_y_offset * c) + (_y_offset * (1 - c));
1146     _z_offset = (_tgt_z_offset * c) + (_z_offset * (1 - c));
1147 }
1148
1149 void FGAIBallistic::formateToAC(double dt){
1150
1151     double hdg, pch, rll = 0;
1152
1153     setTgtOffsets(dt, 25);
1154
1155     if (_pnode != 0) {
1156         setParentPos();
1157         hdg = _p_hdg_node->getDoubleValue();
1158         pch = _p_pch_node->getDoubleValue();
1159         rll = _p_rll_node->getDoubleValue();
1160         setOffsetPos(_parentpos, hdg, pch, rll);
1161         setSpeed(_p_spd_node->getDoubleValue());
1162     }else {
1163         hdg = manager->get_user_heading();
1164         pch = manager->get_user_pitch();
1165         rll = manager->get_user_roll();
1166         setOffsetPos(userpos, hdg, pch, rll);
1167         setSpeed(manager->get_user_speed());
1168     }
1169
1170     // elapsed time has a random initialisation so that each 
1171     // wingman moves differently
1172     _elapsed_time += dt;
1173
1174     // we derive a sine based factor to give us smoothly 
1175     // varying error between -1 and 1
1176     double factor  = sin(SGMiscd::deg2rad(_elapsed_time * 10));
1177     double r_angle = 5 * factor;
1178     double p_angle = 2.5 * factor;
1179     double h_angle = 5 * factor;
1180     double h_feet  = 3 * factor;
1181
1182     pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
1183     pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
1184
1185     if (getHtAGL(10000)){
1186
1187         if(_ht_agl_ft <= 10) {
1188             _height = userpos.getElevationFt();
1189         } else if (_ht_agl_ft > 10 && _ht_agl_ft <= 150 ) {
1190             setHt(userpos.getElevationFt(), dt, 1.0);
1191         } else if (_ht_agl_ft > 150 && _ht_agl_ft <= 250) {
1192             setHt(_offsetpos.getElevationFt()+ h_feet, dt, 0.75);
1193         } else
1194             setHt(_offsetpos.getElevationFt()+ h_feet, dt, 0.5);
1195
1196         pos.setElevationFt(_height);
1197     }
1198
1199     // these calculations are unreliable at slow speeds
1200     if(speed >= 10) {
1201         setHdg(_azimuth + h_angle, dt, 0.9);
1202         setPch(_elevation + p_angle + _pitch_offset, dt, 0.9);
1203
1204         if (roll <= 115 && roll >= -115)
1205             setBnk(manager->get_user_roll() + r_angle + _roll_offset, dt, 0.5);
1206         else
1207             roll = manager->get_user_roll() + r_angle + _roll_offset;
1208
1209     } else {
1210         setHdg(manager->get_user_heading(), dt, 0.9);
1211         setPch(manager->get_user_pitch() + _pitch_offset, dt, 0.9);
1212         setBnk(manager->get_user_roll() + _roll_offset, dt, 0.9);
1213     }
1214
1215         setOffsetVelocity(dt, pos);
1216 }
1217 void FGAIBallistic::calcVSHS(){
1218     // calculate vertical and horizontal speed components
1219     double speed_fps = speed * SG_KT_TO_FPS;
1220
1221     if (speed == 0.0) {
1222         hs = vs = 0.0;
1223     } else {
1224         vs = sin( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1225         hs = cos( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1226     }
1227 }
1228
1229 void FGAIBallistic::calcNE(){
1230     //resolve horizontal speed into north and east components:
1231     _speed_north_fps = cos(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1232     _speed_east_fps = sin(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1233
1234     // convert horizontal speed (fps) to degrees per second
1235     speed_north_deg_sec = _speed_north_fps / ft_per_deg_lat;
1236     speed_east_deg_sec  = _speed_east_fps / ft_per_deg_lon;
1237
1238 }
1239
1240 SGVec3d FGAIBallistic::getCartOffsetPos(SGGeod inpos, double user_heading, 
1241                                         double user_pitch, double user_roll
1242                                         ) const{
1243
1244     // convert geodetic positions to geocentered
1245      SGVec3d cartuserPos = SGVec3d::fromGeod(inpos);
1246     //SGVec3d cartuserPos = getCartUserPos();
1247     //SGVec3d cartPos = getCartPos();
1248
1249     // Transform to the right coordinate frame, configuration is done in
1250     // the x-forward, y-right, z-up coordinates (feet), computation
1251     // in the simulation usual body x-forward, y-right, z-down coordinates
1252     // (meters) )
1253     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1254             _y_offset * SG_FEET_TO_METER,
1255             -_z_offset * SG_FEET_TO_METER);
1256
1257     // Transform the user position to the horizontal local coordinate system.
1258     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
1259
1260     // and postrotate the orientation of the user model wrt the horizontal
1261     // local frame
1262     hlTrans *= SGQuatd::fromYawPitchRollDeg(
1263         user_heading,
1264         user_pitch,
1265         user_roll);
1266
1267     // The offset converted to the usual body fixed coordinate system
1268     // rotated to the earth-fixed coordinates axis
1269     SGVec3d off = hlTrans.backTransform(_off);
1270
1271     // Add the position offset of the user model to get the geocentered position
1272     SGVec3d offsetPos = cartuserPos + off;
1273
1274     return offsetPos;
1275 }
1276
1277 void FGAIBallistic::setOffsetVelocity(double dt, SGGeod offsetpos) {
1278     //calculate the distance from the previous offset position
1279     SGVec3d cartoffsetPos = SGVec3d::fromGeod(offsetpos);
1280     SGVec3d diff = cartoffsetPos - _oldcartoffsetPos;
1281
1282     double distance = norm(diff);
1283     //calculate speed knots
1284     speed = (distance/dt) * SG_MPS_TO_KT;
1285
1286     //now calulate the angle between the old and current postion positions (degrees)
1287     double angle = 0;
1288     double daltM = offsetpos.getElevationM() - _oldoffsetpos.getElevationM();
1289
1290     if (fabs(distance) < SGLimits<float>::min()) {
1291         angle = 0;
1292     } else {
1293         double sAngle = daltM/distance;
1294         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1295         angle = SGMiscd::rad2deg(asin(sAngle));
1296     }
1297
1298     _elevation = angle;
1299
1300     //calculate vertical and horizontal speed components
1301     calcVSHS();
1302
1303     //calculate the bearing of the new offset position from the old
1304     double az1, az2, dist;
1305     geo_inverse_wgs_84(_oldoffsetpos, offsetpos, &az1, &az2, &dist);
1306     _azimuth = az1;
1307
1308     //resolve horizontal speed into north and east components:
1309     calcNE();
1310
1311     // and finally store the new values
1312     _oldcartoffsetPos = cartoffsetPos;
1313     _oldoffsetpos = offsetpos;
1314 }
1315
1316 // end AIBallistic