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