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