]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIGroundVehicle.cxx
f5f2b8832dcee3994902195deef2ebfd0ac4d15c
[flightgear.git] / src / AIModel / AIGroundVehicle.cxx
1 // FGAIGroundVehicle - FGAIShip-derived class creates an AI Ground Vehicle
2 // by adding a ground following utility
3 //
4 // Written by Vivian Meazza, started August 2009.
5 // - vivian.meazza at lineone.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/sg_inlines.h>
26
27 #include <Viewer/viewer.hxx>
28 #include <Scenery/scenery.hxx>
29 #include <Airports/dynamics.hxx>
30
31 #include "AIGroundVehicle.hxx"
32
33 FGAIGroundVehicle::FGAIGroundVehicle() :
34 FGAIShip(otGroundVehicle),
35
36 _pitch(0),
37 _pitch_deg(0),
38 _speed_kt(0),
39 _range_ft(0),
40 _relbrg (0),
41 _parent_speed(0),
42 _parent_x_offset(0),
43 _parent_y_offset(0),
44 _parent_z_offset(0),
45 _dt_count(0),
46 _next_run(0),
47 _break_count(0)
48
49 {
50     invisible = false;
51     _parent = "";
52 }
53
54 FGAIGroundVehicle::~FGAIGroundVehicle() {}
55
56 void FGAIGroundVehicle::readFromScenario(SGPropertyNode* scFileNode) {
57     if (!scFileNode)
58         return;
59
60     FGAIShip::readFromScenario(scFileNode);
61
62     setName(scFileNode->getStringValue("name", "groundvehicle"));
63     setParentName(scFileNode->getStringValue("parent", ""));
64     setNoRoll(scFileNode->getBoolValue("no-roll", true));
65     setContactX1offset(scFileNode->getDoubleValue("contact-x1-offset", 0.0));
66     setContactX2offset(scFileNode->getDoubleValue("contact-x2-offset", 0.0));
67     setXOffset(scFileNode->getDoubleValue("hitch-x-offset", 35.0));
68     setYOffset(scFileNode->getDoubleValue("hitch-y-offset", 0.0));
69     setZOffset(scFileNode->getDoubleValue("hitch-z-offset", 0.0));
70     setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
71     setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
72     setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
73     setPitchCoeff(scFileNode->getDoubleValue("pitch-coefficient", 0.1));
74     setElevCoeff(scFileNode->getDoubleValue("elevation-coefficient", 0.25));
75     setTowAngleGain(scFileNode->getDoubleValue("tow-angle-gain", 1.0));
76     setTowAngleLimit(scFileNode->getDoubleValue("tow-angle-limit-deg", 2.0));
77     setInitialTunnel(scFileNode->getBoolValue("tunnel", false));
78     //we may need these later for towed vehicles
79     //    setSubID(scFileNode->getIntValue("SubID", 0));
80     //    setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
81     //    setFormate(scFileNode->getBoolValue("formate", true));
82 }
83
84 void FGAIGroundVehicle::bind() {
85     FGAIShip::bind();
86
87     tie("controls/constants/elevation-coeff",
88         SGRawValuePointer<double>(&_elevation_coeff));
89     tie("controls/constants/pitch-coeff",
90         SGRawValuePointer<double>(&_pitch_coeff));
91     tie("position/ht-AGL-ft",
92         SGRawValuePointer<double>(&_ht_agl_ft));
93     tie("hitch/rel-bearing-deg",
94          SGRawValuePointer<double>(&_relbrg));
95     tie("hitch/tow-angle-deg",
96          SGRawValuePointer<double>(&_tow_angle));
97     tie("hitch/range-ft",
98         SGRawValuePointer<double>(&_range_ft));
99     tie("hitch/x-offset-ft",
100         SGRawValuePointer<double>(&_x_offset));
101     tie("hitch/y-offset-ft",
102         SGRawValuePointer<double>(&_y_offset));
103     tie("hitch/z-offset-ft",
104         SGRawValuePointer<double>(&_z_offset));
105     tie("hitch/parent-x-offset-ft",
106         SGRawValuePointer<double>(&_parent_x_offset));
107     tie("hitch/parent-y-offset-ft",
108         SGRawValuePointer<double>(&_parent_y_offset));
109     tie("hitch/parent-z-offset-ft",
110         SGRawValuePointer<double>(&_parent_z_offset));
111     tie("controls/constants/tow-angle/gain",
112         SGRawValuePointer<double>(&_tow_angle_gain));
113     tie("controls/constants/tow-angle/limit-deg",
114         SGRawValuePointer<double>(&_tow_angle_limit));
115     tie("controls/contact-x1-offset-ft",
116         SGRawValuePointer<double>(&_contact_x1_offset));
117     tie("controls/contact-x2-offset-ft",
118         SGRawValuePointer<double>(&_contact_x2_offset));
119 }
120
121 bool FGAIGroundVehicle::init(bool search_in_AI_path) {
122     if (!FGAIShip::init(search_in_AI_path))
123         return false;
124     reinit();
125     return true;
126 }
127
128 void FGAIGroundVehicle::reinit() {
129     invisible = false;
130     _limit = 200;
131     no_roll = true;
132
133     props->setStringValue("controls/parent-name", _parent.c_str());
134
135     if (setParentNode()){
136         _parent_x_offset = _selected_ac->getDoubleValue("hitch/x-offset-ft");
137         _parent_y_offset = _selected_ac->getDoubleValue("hitch/y-offset-ft");
138         _parent_z_offset = _selected_ac->getDoubleValue("hitch/z-offset-ft");
139         _hitch_x_offset_m = _selected_ac->getDoubleValue("hitch/x-offset-ft")
140             * SG_FEET_TO_METER;
141         _hitch_y_offset_m = _selected_ac->getDoubleValue("hitch/y-offset-ft")
142             * SG_FEET_TO_METER;
143         _hitch_z_offset_m = _selected_ac->getDoubleValue("hitch/z-offset-ft")
144             * SG_FEET_TO_METER;
145         setParent();
146     }
147
148     FGAIShip::reinit();
149 }
150
151 void FGAIGroundVehicle::update(double dt) {
152     //    SG_LOG(SG_AI, SG_ALERT, "updating GroundVehicle: " << _name );
153     FGAIShip::update(dt);
154
155     RunGroundVehicle(dt);
156 }
157
158 void FGAIGroundVehicle::setNoRoll(bool nr) {
159     no_roll = nr;
160 }
161
162 void FGAIGroundVehicle::setContactX1offset(double x1) {
163     _contact_x1_offset = x1;
164 }
165
166 void FGAIGroundVehicle::setContactX2offset(double x2) {
167     _contact_x2_offset = x2;
168 }
169
170 void FGAIGroundVehicle::setXOffset(double x) {
171     _x_offset = x;
172 }
173
174 void FGAIGroundVehicle::setYOffset(double y) {
175     _y_offset = y;
176 }
177
178 void FGAIGroundVehicle::setZOffset(double z) {
179     _z_offset = z;
180 }
181
182 void FGAIGroundVehicle::setPitchCoeff(double pc) {
183     _pitch_coeff = pc;
184 }
185
186 void FGAIGroundVehicle::setElevCoeff(double ec) {
187     _elevation_coeff = ec;
188 }
189
190 void FGAIGroundVehicle::setTowAngleGain(double g) {
191     _tow_angle_gain = g;
192 }
193
194 void FGAIGroundVehicle::setTowAngleLimit(double l) {
195     _tow_angle_limit = l;
196 }
197
198 void FGAIGroundVehicle::setElevation(double h, double dt, double coeff){
199     double c = dt / (coeff + dt);
200     _elevation_ft = (h * c) + (_elevation_ft * (1 - c));
201 }
202
203 void FGAIGroundVehicle::setPitch(double p, double dt, double coeff){
204     double c = dt / (coeff + dt);
205     _pitch_deg = (p * c) + (_pitch_deg * (1 - c));
206 }
207
208 void FGAIGroundVehicle::setTowAngle(double ta, double dt, double coeff){
209     ta *= _tow_angle_gain;
210     double factor = -0.0045 * speed + 1;
211     double limit = _tow_angle_limit * factor;
212 //      cout << "speed "<< speed << " _factor " << _factor<<" " <<_tow_angle_limit<< endl; 
213      _tow_angle = pow(ta,2) * sign(ta) * factor;
214     SG_CLAMP_RANGE(_tow_angle, -limit, limit);
215 }
216
217 bool FGAIGroundVehicle::getPitch() {
218
219     if (!_tunnel){
220         double vel = props->getDoubleValue("velocities/true-airspeed-kt", 0);
221         double contact_offset_x1_m = _contact_x1_offset * SG_FEET_TO_METER;
222         double contact_offset_x2_m = _contact_x2_offset * SG_FEET_TO_METER;
223         double _z_offset_m = _parent_z_offset * SG_FEET_TO_METER;
224
225         SGVec3d front(-contact_offset_x1_m, 0, 0);
226         SGVec3d rear(-contact_offset_x2_m, 0, 0);
227         SGVec3d Front = getCartPosAt(front);
228         SGVec3d Rear = getCartPosAt(rear);
229
230         SGGeod geodFront = SGGeod::fromCart(Front);
231         SGGeod geodRear = SGGeod::fromCart(Rear);
232
233         double front_elev_m = 0;
234         double rear_elev_m = 0;
235         double elev_front = 0;
236         double elev_rear = 0;
237         //double max_alt = 10000;
238
239         if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodFront, 3000),
240             elev_front, &_material, 0)){
241                 front_elev_m = elev_front + _z_offset_m;
242         } else
243             return false;
244
245         if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodRear, 3000),
246             elev_rear, &_material, 0)){
247                 rear_elev_m = elev_rear;
248         } else
249             return false;
250
251         if (vel >= 0){
252             double diff = front_elev_m - rear_elev_m;
253             _pitch = atan2 (diff,
254                 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
255             _elevation = (rear_elev_m + diff/2) * SG_METER_TO_FEET;
256         } else {
257             double diff = rear_elev_m - front_elev_m;
258             _pitch = atan2 (diff,
259                 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
260             _elevation = (front_elev_m + diff/2) * SG_METER_TO_FEET;
261             _pitch = -_pitch;
262         }
263
264     } else {
265
266         if (prev->getAltitude() == 0 || curr->getAltitude() == 0) return false;
267
268         static double distance;
269         static double d_alt;
270         static double curr_alt;
271         static double prev_alt;
272
273         if (_new_waypoint){
274             //cout << "new waypoint, calculating pitch " << endl;
275             curr_alt = curr->getAltitude();
276             prev_alt = prev->getAltitude();
277             //cout << "prev_alt" <<prev_alt << endl;
278             d_alt = (curr_alt - prev_alt) * SG_METER_TO_FEET;
279             //_elevation = prev->altitude;
280             distance = SGGeodesy::distanceM(SGGeod::fromDeg(prev->getLongitude(), prev->getLatitude()),
281             SGGeod::fromDeg(curr->getLongitude(), curr->getLatitude()));
282             _pitch = atan2(d_alt, distance * SG_METER_TO_FEET) * SG_RADIANS_TO_DEGREES;
283             //cout << "new waypoint, calculating pitch " <<  _pitch << 
284             //    " " << _pitch_offset << " " << _elevation <<endl;
285         }
286
287         double distance_to_go = SGGeodesy::distanceM(SGGeod::fromDeg(pos.getLongitudeDeg(), pos.getLatitudeDeg()),
288             SGGeod::fromDeg(curr->getLongitude(), curr->getLatitude()));
289
290         /*cout << "tunnel " << _tunnel
291              << " distance prev & curr " << prev->name << " " << curr->name << " " << distance * SG_METER_TO_FEET
292              << " distance to go " << distance_to_go * SG_METER_TO_FEET
293              << " d_alt ft " << d_alt
294              << endl;*/
295
296         if (distance_to_go > distance)
297             _elevation = prev_alt;
298         else
299             _elevation = curr_alt - (tan(_pitch * SG_DEGREES_TO_RADIANS) * distance_to_go * SG_METER_TO_FEET);
300
301     }
302
303     return true;
304 }
305
306 void FGAIGroundVehicle::setParent(){
307
308     double lat = _selected_ac->getDoubleValue("position/latitude-deg");
309     double lon = _selected_ac->getDoubleValue("position/longitude-deg");
310     double elevation = _selected_ac->getDoubleValue("position/altitude-ft");
311
312     _selectedpos.setLatitudeDeg(lat);
313     _selectedpos.setLongitudeDeg(lon);
314     _selectedpos.setElevationFt(elevation);
315
316     _parent_speed = _selected_ac->getDoubleValue("velocities/true-airspeed-kt");
317
318     SGVec3d rear_hitch(-_hitch_x_offset_m, _hitch_y_offset_m, 0);
319     SGVec3d RearHitch = getCartHitchPosAt(rear_hitch);
320
321     SGGeod rearpos = SGGeod::fromCart(RearHitch);
322
323     double user_lat = rearpos.getLatitudeDeg();
324     double user_lon = rearpos.getLongitudeDeg();
325
326     double range, bearing;
327
328     calcRangeBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
329         user_lat, user_lon, range, bearing);
330     _range_ft = range * 6076.11549;
331     _relbrg = calcRelBearingDeg(bearing, hdg);
332 }
333
334 void FGAIGroundVehicle::calcRangeBearing(double lat, double lon, double lat2, double lon2,
335                             double &range, double &bearing) const
336 {
337     // calculate the bearing and range of the second pos from the first
338     double az2, distance;
339     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
340     range = distance * SG_METER_TO_NM;
341 }
342
343
344 SGVec3d FGAIGroundVehicle::getCartHitchPosAt(const SGVec3d& _off) const {
345     double hdg = _selected_ac->getDoubleValue("orientation/true-heading-deg");
346     double pitch = _selected_ac->getDoubleValue("orientation/pitch-deg");
347     double roll = _selected_ac->getDoubleValue("orientation/roll-deg");
348
349     // Transform that one to the horizontal local coordinate system.
350     SGQuatd hlTrans = SGQuatd::fromLonLat(_selectedpos);
351
352     // and postrotate the orientation of the AIModel wrt the horizontal
353     // local frame
354     hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
355
356     // The offset converted to the usual body fixed coordinate system
357     // rotated to the earth fiexed coordinates axis
358     SGVec3d off = hlTrans.backTransform(_off);
359
360     // Add the position offset of the AIModel to gain the earth centered position
361     SGVec3d cartPos = SGVec3d::fromGeod(_selectedpos);
362
363     return cartPos + off;
364 }
365
366 void FGAIGroundVehicle::AdvanceFP(){
367
368     double count = 0;
369     string parent_next_name =_selected_ac->getStringValue("waypoint/name-next");
370
371     while(fp->getNextWaypoint() != 0 && fp->getNextWaypoint()->getName() != "END" && count < 5){
372         SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
373             <<" advancing waypoint to: " << parent_next_name);
374
375         if (fp->getNextWaypoint()->getName() == parent_next_name){
376             SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
377                 << " not setting waypoint already at: " << fp->getNextWaypoint()->getName());
378             return;
379         }
380
381         prev = curr;
382         fp->IncrementWaypoint(false);
383         curr = fp->getCurrentWaypoint();
384         next = fp->getNextWaypoint();
385
386         if (fp->getNextWaypoint()->getName() == parent_next_name){
387             SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
388             << " waypoint set to: " << fp->getNextWaypoint()->getName());
389             return;
390         }
391
392         count++;
393
394     }// end while loop
395
396     while(fp->getPreviousWaypoint() != 0 && fp->getPreviousWaypoint()->getName() != "END"
397         && count > -10){
398             SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
399             << " retreating waypoint to: " << parent_next_name
400             << " at: " << fp->getNextWaypoint()->getName());
401
402         if (fp->getNextWaypoint()->getName() == parent_next_name){
403             SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
404                 << " not setting waypoint already at:" << fp->getNextWaypoint()->getName() );
405             return;
406         }
407
408         prev = curr;
409         fp->DecrementWaypoint(false);
410         curr = fp->getCurrentWaypoint();
411         next = fp->getNextWaypoint();
412
413         if (fp->getNextWaypoint()->getName() == parent_next_name){
414             SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
415             << " waypoint set to: " << fp->getNextWaypoint()->getName());
416             return;
417         }
418
419         count--;
420
421     }// end while loop
422 }
423
424 void FGAIGroundVehicle::setTowSpeed(){
425
426     //double diff = _range_ft - _x_offset;
427     double  x = 0;
428
429     if (_range_ft > _x_offset * 3) x = 50;
430
431     if (_relbrg < -90 || _relbrg > 90){
432         setSpeed(_parent_speed - 5 - x);
433         //cout << _name << " case 1r _relbrg spd - 5 " << _relbrg << " " << diff << endl;
434     }else if (_range_ft > _x_offset + 0.25 && _relbrg >= -90 && _relbrg <= 90){
435         setSpeed(_parent_speed + 1 + x);
436         //cout << _name << " case 2r _relbrg spd + 1 " << _relbrg << " "
437         //    << diff << " range " << _range_ft << endl;
438     } else if (_range_ft < _x_offset - 0.25 && _relbrg >= -90 && _relbrg <= 90){
439         setSpeed(_parent_speed - 1 - x);
440         //cout << _name << " case 3r _relbrg spd - 2 " << _relbrg << " "
441         //    << diff << " " << _range_ft << endl;
442     } else {
443         setSpeed(_parent_speed);
444         //cout << _name << " else r _relbrg " << _relbrg << " " << diff << endl;
445     }
446
447 }
448
449 void FGAIGroundVehicle::RunGroundVehicle(double dt){
450
451     _dt_count += dt;
452
453     ///////////////////////////////////////////////////////////////////////////
454     // Check execution time (currently once every 0.05 sec or 20 fps)
455     // Add a bit of randomization to prevent the execution of all flight plans
456     // in synchrony, which can add significant periodic framerate flutter.
457     // Randomization removed to get better appearance
458     ///////////////////////////////////////////////////////////////////////////
459
460     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
461     if (_dt_count < _next_run)
462         return;
463
464     _next_run = 0.05 /*+ (0.015 * sg_random())*/;
465
466     if (getPitch()){
467         setElevation(_elevation, _dt_count, _elevation_coeff);
468         ClimbTo(_elevation_ft);
469         setPitch(_pitch, _dt_count, _pitch_coeff);
470         PitchTo(_pitch_deg);
471     }
472
473     if(_parent == ""){
474         AccelTo(prev->getSpeed());
475         _dt_count = 0;
476         return;
477     }
478
479     setParent();
480
481     string parent_next_name = _selected_ac->getStringValue("waypoint/name-next");
482     bool parent_waiting = _selected_ac->getBoolValue("waypoint/waiting");
483     //bool parent_restart = _selected_ac->getBoolValue("controls/restart"); 
484
485     if (parent_next_name == "END" && fp->getNextWaypoint()->getName() != "END" ){
486         SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
487             << " setting END: getting new waypoints ");
488         AdvanceFP();
489         setWPNames();
490         setTunnel(_initial_tunnel);
491         if(_restart) _missed_count = 200;
492         /*} else if (parent_next_name == "WAIT" && fp->getNextWaypoint()->name != "WAIT" ){*/
493     } else if (parent_waiting && !_waiting){
494         SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
495             << " setting WAIT/WAITUNTIL: getting new waypoints ");
496         AdvanceFP();
497         setWPNames();
498         _waiting = true;
499     } else if (parent_next_name != "WAIT" && fp->getNextWaypoint()->getName() == "WAIT"){
500         SG_LOG(SG_AI, SG_DEBUG, "AIGroundVeh1cle: " << _name
501             << " wait done: getting new waypoints ");
502         _waiting = false;
503         _wait_count = 0;
504         fp->IncrementWaypoint(false);
505         next = fp->getNextWaypoint();
506
507         if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
508             || next->getName() == "END"){
509         } else {
510             prev = curr;
511             fp->IncrementWaypoint(false);
512             curr = fp->getCurrentWaypoint();
513             next = fp->getNextWaypoint();
514         }
515
516         setWPNames();
517     } else if (_range_ft > (_x_offset +_parent_x_offset)* 4
518         ){
519         SG_LOG(SG_AI, SG_ALERT, "AIGroundVeh1cle: " << _name
520             << " rescue: reforming train " << _range_ft 
521             );
522
523         setTowAngle(0, dt, 1);
524         setSpeed(_parent_speed + (10 * sign(_parent_speed)));
525
526     } else if (_parent_speed > 1){
527
528         setTowSpeed();
529         setTowAngle(_relbrg, dt, 1);
530
531     } else if (_parent_speed < -1){
532
533         setTowSpeed();
534
535         if (_relbrg < 0)
536             setTowAngle(-(180 - (360 + _relbrg)), dt, 1);
537         else
538             setTowAngle(-(180 - _relbrg), dt, 1);
539
540     } else
541         setSpeed(_parent_speed);
542
543 //    FGAIShip::update(_dt_count);
544     _dt_count = 0;
545
546 }
547
548 // end AIGroundvehicle