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