1 // FGAIGroundVehicle - FGAIShip-derived class creates an AI Ground Vehicle
2 // by adding a ground following utility
4 // Written by Vivian Meazza, started August 2009.
5 // - vivian.meazza at lineone.net
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.
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.
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.
25 #include <simgear/sg_inlines.h>
27 #include <Main/viewer.hxx>
28 #include <Scenery/scenery.hxx>
29 #include <Scenery/tilemgr.hxx>
30 #include <Airports/dynamics.hxx>
32 #include "AIGroundVehicle.hxx"
34 FGAIGroundVehicle::FGAIGroundVehicle() :
35 FGAIShip(otGroundVehicle),
56 FGAIGroundVehicle::~FGAIGroundVehicle() {}
58 void FGAIGroundVehicle::readFromScenario(SGPropertyNode* scFileNode) {
62 FGAIShip::readFromScenario(scFileNode);
64 setNoRoll(scFileNode->getBoolValue("no-roll", true));
65 setName(scFileNode->getStringValue("name", "groundvehicle"));
66 setSMPath(scFileNode->getStringValue("submodel-path", ""));
67 setContactX1offset(scFileNode->getDoubleValue("contact-x1-offset", 0.0));
68 setContactX2offset(scFileNode->getDoubleValue("contact-x2-offset", 0.0));
69 setXOffset(scFileNode->getDoubleValue("hitch-x-offset", 35.0));
70 setYOffset(scFileNode->getDoubleValue("hitch-y-offset", 0.0));
71 setZOffset(scFileNode->getDoubleValue("hitch-z-offset", 0.0));
72 setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
73 setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
74 setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
75 setPitchCoeff(scFileNode->getDoubleValue("pitch-coefficient", 0.1));
76 setElevCoeff(scFileNode->getDoubleValue("elevation-coefficient", 0.25));
77 setParentName(scFileNode->getStringValue("parent", ""));
78 setTowAngleGain(scFileNode->getDoubleValue("tow-angle-gain", 1.0));
79 setTowAngleLimit(scFileNode->getDoubleValue("tow-angle-limit-deg", 2.0));
80 setInitialTunnel(scFileNode->getBoolValue("tunnel", false));
81 //we may need these later for towed vehicles
82 // setSubID(scFileNode->getIntValue("SubID", 0));
83 // setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
84 // setFormate(scFileNode->getBoolValue("formate", true));
87 void FGAIGroundVehicle::bind() {
90 props->tie("controls/constants/elevation-coeff",
91 SGRawValuePointer<double>(&_elevation_coeff));
92 props->tie("controls/constants/pitch-coeff",
93 SGRawValuePointer<double>(&_pitch_coeff));
94 props->tie("position/ht-AGL-ft",
95 SGRawValuePointer<double>(&_ht_agl_ft));
96 props->tie("hitch/rel-bearing-deg",
97 SGRawValuePointer<double>(&_relbrg));
98 props->tie("hitch/tow-angle-deg",
99 SGRawValuePointer<double>(&_tow_angle));
100 props->tie("hitch/range-ft",
101 SGRawValuePointer<double>(&_range_ft));
102 props->tie("hitch/x-offset-ft",
103 SGRawValuePointer<double>(&_x_offset));
104 props->tie("hitch/y-offset-ft",
105 SGRawValuePointer<double>(&_y_offset));
106 props->tie("hitch/z-offset-ft",
107 SGRawValuePointer<double>(&_z_offset));
108 props->tie("hitch/parent-x-offset-ft",
109 SGRawValuePointer<double>(&_parent_x_offset));
110 props->tie("hitch/parent-y-offset-ft",
111 SGRawValuePointer<double>(&_parent_y_offset));
112 props->tie("hitch/parent-z-offset-ft",
113 SGRawValuePointer<double>(&_parent_z_offset));
114 props->tie("controls/constants/tow-angle/gain",
115 SGRawValuePointer<double>(&_tow_angle_gain));
116 props->tie("controls/constants/tow-angle/limit-deg",
117 SGRawValuePointer<double>(&_tow_angle_limit));
118 props->tie("controls/contact-x1-offset-ft",
119 SGRawValuePointer<double>(&_contact_x1_offset));
120 props->tie("controls/contact-x2-offset-ft",
121 SGRawValuePointer<double>(&_contact_x2_offset));
124 void FGAIGroundVehicle::unbind() {
127 props->untie("controls/constants/elevation-coeff");
128 props->untie("controls/constants/pitch-coeff");
129 props->untie("position/ht-AGL-ft");
130 props->untie("hitch/rel-bearing-deg");
131 props->untie("hitch/tow-angle-deg");
132 props->untie("hitch/range-ft");
133 props->untie("hitch/x-offset-ft");
134 props->untie("hitch/y-offset-ft");
135 props->untie("hitch/z-offset-ft");
136 props->untie("hitch/parent-x-offset-ft");
137 props->untie("hitch/parent-y-offset-ft");
138 props->untie("hitch/parent-y-offset-ft");
139 props->untie("controls/constants/tow-angle/gain");
140 props->untie("controls/constants/tow-angle/limit-deg");
141 props->untie("controls/contact-x1-offset-ft");
142 props->untie("controls/contact-x2-offset-ft");
145 bool FGAIGroundVehicle::init(bool search_in_AI_path) {
146 if (!FGAIShip::init(search_in_AI_path))
156 void FGAIGroundVehicle::update(double dt) {
157 // SG_LOG(SG_GENERAL, SG_ALERT, "updating GroundVehicle: " << _name );
158 FGAIShip::update(dt);
160 RunGroundVehicle(dt);
163 void FGAIGroundVehicle::setNoRoll(bool nr) {
167 void FGAIGroundVehicle::setContactX1offset(double x1) {
168 _contact_x1_offset = x1;
171 void FGAIGroundVehicle::setContactX2offset(double x2) {
172 _contact_x2_offset = x2;
175 void FGAIGroundVehicle::setXOffset(double x) {
179 void FGAIGroundVehicle::setYOffset(double y) {
183 void FGAIGroundVehicle::setZOffset(double z) {
187 void FGAIGroundVehicle::setPitchCoeff(double pc) {
191 void FGAIGroundVehicle::setElevCoeff(double ec) {
192 _elevation_coeff = ec;
195 void FGAIGroundVehicle::setTowAngleGain(double g) {
199 void FGAIGroundVehicle::setTowAngleLimit(double l) {
200 _tow_angle_limit = l;
203 void FGAIGroundVehicle::setElevation(double h, double dt, double coeff){
204 double c = dt / (coeff + dt);
205 _elevation_ft = (h * c) + (_elevation_ft * (1 - c));
208 void FGAIGroundVehicle::setPitch(double p, double dt, double coeff){
209 double c = dt / (coeff + dt);
210 _pitch_deg = (p * c) + (_pitch_deg * (1 - c));
213 void FGAIGroundVehicle::setParentName(const string& p) {
217 void FGAIGroundVehicle::setTowAngle(double ta, double dt, double coeff){
218 ta *= _tow_angle_gain;
219 double factor = -0.0045 * speed + 1;
220 double limit = _tow_angle_limit * factor;
221 // cout << "speed "<< speed << " _factor " << _factor<<" " <<_tow_angle_limit<< endl;
222 _tow_angle = pow(ta,2) * sign(ta) * factor;
223 SG_CLAMP_RANGE(_tow_angle, -limit, limit);
226 bool FGAIGroundVehicle::getGroundElev(SGGeod inpos) {
230 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(inpos, 3000), height_m, &_material,0)){
231 _ht_agl_ft = inpos.getElevationFt() - height_m * SG_METER_TO_FEET;
234 const vector<string>& names = _material->get_names();
236 _solid = _material->get_solid();
239 props->setStringValue("material/name", names[0].c_str());
241 props->setStringValue("material/name", "");
243 //cout << "material " << names[0].c_str()
244 // << " _elevation_m " << _elevation_m
245 // << " solid " << _solid
246 // << " load " << _load_resistance
247 // << " frictionFactor " << _frictionFactor
259 bool FGAIGroundVehicle::getPitch() {
262 double vel = props->getDoubleValue("velocities/true-airspeed-kt", 0);
263 double contact_offset_x1_m = _contact_x1_offset * SG_FEET_TO_METER;
264 double contact_offset_x2_m = _contact_x2_offset * SG_FEET_TO_METER;
265 double _z_offset_m = _parent_z_offset * SG_FEET_TO_METER;
267 SGVec3d front(-contact_offset_x1_m, 0, 0);
268 SGVec3d rear(-contact_offset_x2_m, 0, 0);
269 SGVec3d Front = getCartPosAt(front);
270 SGVec3d Rear = getCartPosAt(rear);
272 SGGeod geodFront = SGGeod::fromCart(Front);
273 SGGeod geodRear = SGGeod::fromCart(Rear);
275 double front_elev_m = 0;
276 double rear_elev_m = 0;
277 double elev_front = 0;
278 double elev_rear = 0;
279 double max_alt = 10000;
281 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodFront, 3000),
282 elev_front, &_material, 0)){
283 front_elev_m = elev_front + _z_offset_m;
287 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodRear, 3000),
288 elev_rear, &_material, 0)){
289 rear_elev_m = elev_rear;
294 double diff = front_elev_m - rear_elev_m;
295 _pitch = atan2 (diff,
296 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
297 _elevation = (rear_elev_m + diff/2) * SG_METER_TO_FEET;
299 double diff = rear_elev_m - front_elev_m;
300 _pitch = atan2 (diff,
301 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
302 _elevation = (front_elev_m + diff/2) * SG_METER_TO_FEET;
308 if (prev->altitude == 0 || curr->altitude == 0) return false;
310 static double distance;
312 static double curr_alt;
313 static double prev_alt;
316 //cout << "new waypoint, calculating pitch " << endl;
317 curr_alt = curr->altitude;
318 prev_alt = prev->altitude;
319 //cout << "prev_alt" <<prev_alt << endl;
320 d_alt = (curr_alt - prev_alt) * SG_METER_TO_FEET;
321 //_elevation = prev->altitude;
322 distance = SGGeodesy::distanceM(SGGeod::fromDeg(prev->longitude, prev->latitude),
323 SGGeod::fromDeg(curr->longitude, curr->latitude));
324 _pitch = atan2(d_alt, distance * SG_METER_TO_FEET) * SG_RADIANS_TO_DEGREES;
325 //cout << "new waypoint, calculating pitch " << _pitch <<
326 // " " << _pitch_offset << " " << _elevation <<endl;
329 double distance_to_go = SGGeodesy::distanceM(SGGeod::fromDeg(pos.getLongitudeDeg(), pos.getLatitudeDeg()),
330 SGGeod::fromDeg(curr->longitude, curr->latitude));
332 /*cout << "tunnel " << _tunnel
333 << " distance prev & curr " << prev->name << " " << curr->name << " " << distance * SG_METER_TO_FEET
334 << " distance to go " << distance_to_go * SG_METER_TO_FEET
335 << " d_alt ft " << d_alt
338 if (distance_to_go > distance)
339 _elevation = prev_alt;
341 _elevation = curr_alt - (tan(_pitch * SG_DEGREES_TO_RADIANS) * distance_to_go * SG_METER_TO_FEET);
350 void FGAIGroundVehicle::setParent() {
352 const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
354 for (int i = ai->nChildren() - 1; i >= -1; i--) {
355 SGPropertyNode_ptr model;
357 if (i < 0) { // last iteration: selected model
358 model = _selected_ac;
360 model = ai->getChild(i);
361 string path = ai->getPath();
362 const string name = model->getStringValue("name");
364 if (!model->nChildren()){
367 if (name == _parent) {
368 _selected_ac = model; // save selected model for last iteration
378 if (_selected_ac != 0){
379 const string name = _selected_ac->getStringValue("name");
380 double lat = _selected_ac->getDoubleValue("position/latitude-deg");
381 double lon = _selected_ac->getDoubleValue("position/longitude-deg");
382 double elevation = _selected_ac->getDoubleValue("position/altitude-ft");
383 double hitch_x_offset_m = _selected_ac->getDoubleValue("hitch/x-offset-ft")
385 double hitch_y_offset_m = _selected_ac->getDoubleValue("hitch/y-offset-ft")
387 double hitch_z_offset_m = _selected_ac->getDoubleValue("hitch/z-offset-ft")
390 _selectedpos.setLatitudeDeg(lat);
391 _selectedpos.setLongitudeDeg(lon);
392 _selectedpos.setElevationFt(elevation);
394 _parent_x_offset = _selected_ac->getDoubleValue("hitch/x-offset-ft");
395 _parent_y_offset = _selected_ac->getDoubleValue("hitch/y-offset-ft");
396 _parent_z_offset = _selected_ac->getDoubleValue("hitch/z-offset-ft");
398 _parent_speed = _selected_ac->getDoubleValue("velocities/true-airspeed-kt");
400 SGVec3d rear_hitch(-hitch_x_offset_m, hitch_y_offset_m, 0);
401 SGVec3d RearHitch = getCartHitchPosAt(rear_hitch);
403 SGGeod rearpos = SGGeod::fromCart(RearHitch);
405 double user_lat = rearpos.getLatitudeDeg();
406 double user_lon = rearpos.getLongitudeDeg();
408 double range, bearing;
410 calcRangeBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
411 user_lat, user_lon, range, bearing);
412 _range_ft = range * 6076.11549;
413 _relbrg = calcRelBearingDeg(bearing, hdg);
415 SG_LOG(SG_GENERAL, SG_ALERT, "AIGroundVeh1cle: " << _name
416 << " parent not found: dying ");
422 void FGAIGroundVehicle::calcRangeBearing(double lat, double lon, double lat2, double lon2,
423 double &range, double &bearing) const
425 // calculate the bearing and range of the second pos from the first
426 double az2, distance;
427 geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
428 range = distance * SG_METER_TO_NM;
431 double FGAIGroundVehicle::calcRelBearingDeg(double bearing, double heading)
433 double angle = bearing - heading;
434 SG_NORMALIZE_RANGE(angle, -180.0, 180.0);
438 SGVec3d FGAIGroundVehicle::getCartHitchPosAt(const SGVec3d& _off) const {
439 double hdg = _selected_ac->getDoubleValue("orientation/true-heading-deg");
440 double pitch = _selected_ac->getDoubleValue("orientation/pitch-deg");
441 double roll = _selected_ac->getDoubleValue("orientation/roll-deg");
443 // Transform that one to the horizontal local coordinate system.
444 SGQuatd hlTrans = SGQuatd::fromLonLat(_selectedpos);
446 // and postrotate the orientation of the AIModel wrt the horizontal
448 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
450 // The offset converted to the usual body fixed coordinate system
451 // rotated to the earth fiexed coordinates axis
452 SGVec3d off = hlTrans.backTransform(_off);
454 // Add the position offset of the AIModel to gain the earth centered position
455 SGVec3d cartPos = SGVec3d::fromGeod(_selectedpos);
457 return cartPos + off;
460 void FGAIGroundVehicle::AdvanceFP(){
463 string parent_next_name =_selected_ac->getStringValue("waypoint/name-next");
465 while(fp->getNextWaypoint() != 0 && fp->getNextWaypoint()->name != "END" && count < 5){
466 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
467 <<" advancing waypoint to: " << parent_next_name);
469 if (fp->getNextWaypoint()->name == parent_next_name){
470 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
471 << " not setting waypoint already at: " << fp->getNextWaypoint()->name);
476 fp->IncrementWaypoint(false);
477 curr = fp->getCurrentWaypoint();
478 next = fp->getNextWaypoint();
480 if (fp->getNextWaypoint()->name == parent_next_name){
481 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
482 << " waypoint set to: " << fp->getNextWaypoint()->name);
490 while(fp->getPreviousWaypoint() != 0 && fp->getPreviousWaypoint()->name != "END"
492 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
493 << " retreating waypoint to: " << parent_next_name
494 << " at: " << fp->getNextWaypoint()->name);
496 if (fp->getNextWaypoint()->name == parent_next_name){
497 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
498 << " not setting waypoint already at:" << fp->getNextWaypoint()->name );
503 fp->DecrementWaypoint(false);
504 curr = fp->getCurrentWaypoint();
505 next = fp->getNextWaypoint();
507 if (fp->getNextWaypoint()->name == parent_next_name){
508 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
509 << " waypoint set to: " << fp->getNextWaypoint()->name);
518 void FGAIGroundVehicle::setTowSpeed(){
520 double diff = _range_ft - _x_offset;
523 if (_range_ft > _x_offset * 3) x = 50;
525 if (_relbrg < -90 || _relbrg > 90){
526 setSpeed(_parent_speed - 5 - x);
527 //cout << _name << " case 1r _relbrg spd - 5 " << _relbrg << " " << diff << endl;
528 }else if (_range_ft > _x_offset + 0.25 && _relbrg >= -90 && _relbrg <= 90){
529 setSpeed(_parent_speed + 1 + x);
530 //cout << _name << " case 2r _relbrg spd + 1 " << _relbrg << " "
531 // << diff << " range " << _range_ft << endl;
532 } else if (_range_ft < _x_offset - 0.25 && _relbrg >= -90 && _relbrg <= 90){
533 setSpeed(_parent_speed - 1 - x);
534 //cout << _name << " case 3r _relbrg spd - 2 " << _relbrg << " "
535 // << diff << " " << _range_ft << endl;
537 setSpeed(_parent_speed);
538 //cout << _name << " else r _relbrg " << _relbrg << " " << diff << endl;
543 void FGAIGroundVehicle::RunGroundVehicle(double dt){
547 ///////////////////////////////////////////////////////////////////////////
548 // Check execution time (currently once every 0.05 sec or 20 fps)
549 // Add a bit of randomization to prevent the execution of all flight plans
550 // in synchrony, which can add significant periodic framerate flutter.
551 // Randomization removed to get better appearance
552 ///////////////////////////////////////////////////////////////////////////
554 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
555 if (_dt_count < _next_run)
558 _next_run = 0.05 /*+ (0.015 * sg_random())*/;
561 setElevation(_elevation, _dt_count, _elevation_coeff);
562 ClimbTo(_elevation_ft);
563 setPitch(_pitch, _dt_count, _pitch_coeff);
568 AccelTo(prev->speed);
575 string parent_next_name = _selected_ac->getStringValue("waypoint/name-next");
576 bool parent_waiting = _selected_ac->getBoolValue("waypoint/waiting");
577 bool parent_restart = _selected_ac->getBoolValue("controls/restart");
579 if (parent_next_name == "END" && fp->getNextWaypoint()->name != "END" ){
580 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
581 << " setting END: getting new waypoints ");
584 setTunnel(_initial_tunnel);
585 if(_restart) _missed_count = 200;
586 /*} else if (parent_next_name == "WAIT" && fp->getNextWaypoint()->name != "WAIT" ){*/
587 } else if (parent_waiting && !_waiting){
588 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
589 << " setting WAIT/WAITUNTIL: getting new waypoints ");
593 } else if (parent_next_name != "WAIT" && fp->getNextWaypoint()->name == "WAIT"){
594 SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
595 << " wait done: getting new waypoints ");
598 fp->IncrementWaypoint(false);
599 next = fp->getNextWaypoint();
601 if (next->name == "WAITUNTIL" || next->name == "WAIT"
602 || next->name == "END"){
605 fp->IncrementWaypoint(false);
606 curr = fp->getCurrentWaypoint();
607 next = fp->getNextWaypoint();
611 } else if (_range_ft > (_x_offset +_parent_x_offset)* 4
613 SG_LOG(SG_GENERAL, SG_ALERT, "AIGroundVeh1cle: " << _name
614 << " rescue: reforming train " << _range_ft
617 setTowAngle(0, dt, 1);
618 setSpeed(_parent_speed + (10 * sign(_parent_speed)));
620 } else if (_parent_speed > 1){
623 setTowAngle(_relbrg, dt, 1);
625 } else if (_parent_speed < -1){
630 setTowAngle(-(180 - (360 + _relbrg)), dt, 1);
632 setTowAngle(-(180 - _relbrg), dt, 1);
635 setSpeed(_parent_speed);
637 // FGAIShip::update(_dt_count);
642 // end AIGroundvehicle