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