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