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