]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
Mathias Froehlich: fix refcounting problem that caused submodel crashes
[flightgear.git] / src / AIModel / AIBase.cxx
1 // FGAIBase - abstract base class for AI objects
2 // Written by David Culp, started Nov 2003, based on
3 // David Luff's FGAIEntity class.
4 // - davidculp2@comcast.net
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/compiler.h>
26
27 #include STL_STRING
28
29 #include <plib/sg.h>
30 #include <plib/ssg.h>
31
32 #include <simgear/math/point3d.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/scene/model/location.hxx>
36 #include <simgear/scene/model/model.hxx>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/props/props.hxx>
39
40 #include <Main/globals.hxx>
41 #include <Scenery/scenery.hxx>
42
43
44 #include "AIBase.hxx"
45 #include "AIManager.hxx"
46
47
48 const double FGAIBase::e = 2.71828183;
49 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
50
51
52 FGAIBase::FGAIBase()
53   : fp( NULL ),
54     model( NULL ),
55     props( NULL ),
56     manager( NULL ),
57     _refID( _newAIModelID() )
58 {
59     _type_str = "model";
60     tgt_heading = tgt_altitude = tgt_speed = 0.0;
61     tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
62     bearing = elevation = range = rdot = 0.0;
63     x_shift = y_shift = rotation = 0.0;
64     in_range = false;
65     invisible = true;
66     no_roll = true;
67     life = 900;
68     model_path = "";
69     _otype = otNull;
70     index = 0;
71     delete_me = false;
72 }
73
74 FGAIBase::~FGAIBase() {
75     // Unregister that one at the scenery manager
76     if (globals->get_scenery()) {
77         globals->get_scenery()->unregister_placement_transform(aip.getTransform());
78         globals->get_scenery()->get_scene_graph()->removeKid(aip.getSceneGraph());
79     }
80     // unbind();
81     SGPropertyNode *root = globals->get_props()->getNode("ai/models", true);
82     root->removeChild(_type_str.c_str(), index);
83     delete fp;
84     fp = NULL;
85     ssgDeRefDelete(model);
86     model = 0;
87 }
88
89 void FGAIBase::update(double dt) {
90     if (_otype == otStatic) return;
91     if (_otype == otBallistic) CalculateMach();
92
93     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.lat()*SGD_DEGREES_TO_RADIANS);
94     ft_per_deg_lon = 365228.16 * cos(pos.lat()*SGD_DEGREES_TO_RADIANS);
95 }
96
97 void FGAIBase::Transform() {
98     if (!invisible) {
99       aip.setPosition(pos.lon(), pos.lat(), pos.elev() * SG_METER_TO_FEET);
100       if (no_roll) {
101          aip.setOrientation(0.0, pitch, hdg);
102       } else {
103          aip.setOrientation(roll, pitch, hdg);
104       }
105       aip.update();    
106     }
107 }
108
109
110 bool FGAIBase::init() {
111
112    SGPropertyNode *root = globals->get_props()->getNode("ai/models", true);
113
114    index = manager->getNum(_otype) - 1;
115    props = root->getNode(_type_str.c_str(), index, true);
116
117    if (model_path != "") {
118     try {
119       model = load3DModel( globals->get_fg_root(),
120                              SGPath(model_path).c_str(),
121                              props,
122                              globals->get_sim_time_sec() );
123     } catch (const sg_exception &e) {
124        model = NULL;
125     }
126    }
127    if (model) {
128      aip.init( model );
129      aip.setVisible(true);
130      invisible = false;
131      globals->get_scenery()->get_scene_graph()->addKid(aip.getSceneGraph());
132      // Register that one at the scenery manager
133      globals->get_scenery()->register_placement_transform(aip.getTransform());
134    } else {
135      if (model_path != "") { 
136        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
137      }
138    } 
139
140    setDie(false);
141
142    return true;
143 }
144
145
146 ssgBranch * FGAIBase::load3DModel(const string& fg_root, 
147                                   const string &path,
148                                   SGPropertyNode *prop_root, 
149                                   double sim_time_sec)
150 {
151   // some more code here to check whether a model with this name has already been loaded
152   // if not load it, otherwise, get the memory pointer and do something like 
153   // SetModel as in ATC/AIEntity.cxx
154   //SSGBranch *model;
155   model = manager->getModel(path);
156   if (!(model))
157     {
158       model = sgLoad3DModel(fg_root,
159                             path,
160                             prop_root,
161                             sim_time_sec);
162       manager->setModel(path, model);
163     }
164   //else
165   //  {
166   //    model->ref();
167   //    aip.init(model);
168   //    aip.setVisible(false);
169   //    globals->get_scenery()->get_scene_graph()->addKid(aip.getSceneGraph());
170   // do some setModel stuff.
171   
172   if (model)
173     model->ref();
174
175   return model;
176 }
177
178 bool FGAIBase::isa( object_type otype ) {
179  if ( otype == _otype ) { return true; }
180  else { return false; } 
181 }
182
183
184 void FGAIBase::bind() {
185    props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
186                                          &FGAIBase::getID));
187    props->tie("velocities/true-airspeed-kt",  SGRawValuePointer<double>(&speed));
188    props->tie("velocities/vertical-speed-fps",
189                SGRawValueMethods<FGAIBase,double>(*this,
190                                          &FGAIBase::_getVS_fps,
191                                          &FGAIBase::_setVS_fps));
192
193    props->tie("position/altitude-ft",
194                SGRawValueMethods<FGAIBase,double>(*this,
195                                          &FGAIBase::_getAltitude,
196                                          &FGAIBase::_setAltitude));
197    props->tie("position/latitude-deg",
198                SGRawValueMethods<FGAIBase,double>(*this,
199                                          &FGAIBase::_getLatitude,
200                                          &FGAIBase::_setLatitude));
201    props->tie("position/longitude-deg",
202                SGRawValueMethods<FGAIBase,double>(*this,
203                                          &FGAIBase::_getLongitude,
204                                          &FGAIBase::_setLongitude));
205
206    props->tie("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
207    props->tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
208    props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
209
210    props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
211    props->tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
212    props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
213    props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
214    props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
215    props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset)); 
216    props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
217    props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
218    props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
219
220    props->tie("controls/lighting/nav-lights",
221                SGRawValueFunctions<bool>(_isNight));
222    props->setBoolValue("controls/lighting/beacon", true);
223    props->setBoolValue("controls/lighting/strobe", true);
224    props->setBoolValue("controls/glide-path", true);
225 }
226
227 void FGAIBase::unbind() {
228     props->untie("id");
229     props->untie("velocities/true-airspeed-kt");
230     props->untie("velocities/vertical-speed-fps");
231
232     props->untie("position/altitude-ft");
233     props->untie("position/latitude-deg");
234     props->untie("position/longitude-deg");
235
236     props->untie("orientation/pitch-deg");
237     props->untie("orientation/roll-deg");
238     props->untie("orientation/true-heading-deg");
239
240     props->untie("radar/in-range");
241     props->untie("radar/bearing-deg");
242     props->untie("radar/elevation-deg");
243     props->untie("radar/range-nm");
244     props->untie("radar/h-offset");
245     props->untie("radar/v-offset");
246     props->untie("radar/x-shift");
247     props->untie("radar/y-shift");
248     props->untie("radar/rotation");
249
250     props->untie("controls/lighting/nav-lights");
251 }
252
253 double FGAIBase::UpdateRadar(FGAIManager* manager)
254 {
255    double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
256    radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
257    radar_range_ft2 *= radar_range_ft2;
258
259    double user_latitude  = manager->get_user_latitude();
260    double user_longitude = manager->get_user_longitude();
261    double lat_range = fabs(pos.lat() - user_latitude) * ft_per_deg_lat;
262    double lon_range = fabs(pos.lon() - user_longitude) * ft_per_deg_lon;
263    double range_ft2 = lat_range*lat_range + lon_range*lon_range;
264
265    //
266    // Test whether the target is within radar range.
267    //
268    in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
269    if ( in_range )
270    {
271      props->setBoolValue("radar/in-range", true);
272
273      // copy values from the AIManager
274      double user_altitude  = manager->get_user_altitude();
275      double user_heading   = manager->get_user_heading();
276      double user_pitch     = manager->get_user_pitch();
277      double user_yaw       = manager->get_user_yaw();
278      double user_speed     = manager->get_user_speed();
279
280      // calculate range to target in feet and nautical miles
281      double range_ft = sqrt( range_ft2 );
282      range = range_ft / 6076.11549;
283
284      // calculate bearing to target
285      if (pos.lat() >= user_latitude) {
286         bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
287         if (pos.lon() >= user_longitude) {
288            bearing = 90.0 - bearing;
289         } else {
290            bearing = 270.0 + bearing;
291         }
292      } else {
293         bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
294         if (pos.lon() >= user_longitude) {
295            bearing = 180.0 - bearing;
296         } else {
297            bearing = 180.0 + bearing;
298         }
299      }
300
301      // calculate look left/right to target, without yaw correction
302      horiz_offset = bearing - user_heading;
303      if (horiz_offset > 180.0) horiz_offset -= 360.0;
304      if (horiz_offset < -180.0) horiz_offset += 360.0;
305
306      // calculate elevation to target
307      elevation = atan2( altitude * SG_METER_TO_FEET - user_altitude, range_ft )
308                         * SG_RADIANS_TO_DEGREES;
309
310      // calculate look up/down to target
311      vert_offset = elevation + user_pitch;
312
313      /* this calculation needs to be fixed, but it isn't important anyway
314      // calculate range rate
315      double recip_bearing = bearing + 180.0;
316      if (recip_bearing > 360.0) recip_bearing -= 360.0;
317      double my_horiz_offset = recip_bearing - hdg;
318      if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
319      if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
320      rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
321              +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
322 */
323
324      // now correct look left/right for yaw
325      horiz_offset += user_yaw;
326
327      // calculate values for radar display
328      y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
329      x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
330      rotation = hdg - user_heading;
331      if (rotation < 0.0) rotation += 360.0;
332
333    }
334
335    return range_ft2;
336 }
337
338 Point3D
339 FGAIBase::getCartPosAt(const Point3D& off) const
340 {
341   // The offset converted to the usual body fixed coordinate system.
342   sgdVec3 sgdOff;
343   sgdSetVec3(sgdOff, -off.x(), off.z(), -off.y());
344
345   // Transform that one to the horizontal local coordinate system.
346   sgdMat4 hlTrans;
347   sgdMakeRotMat4(hlTrans, hdg, pitch, roll);
348   sgdXformPnt3(sgdOff, hlTrans);
349
350   // Now transform to the wgs84 earth centeres system.
351   Point3D pos2(pos.lon()* SGD_DEGREES_TO_RADIANS,
352                pos.lat() * SGD_DEGREES_TO_RADIANS,
353                pos.elev());
354   Point3D cartPos3D = sgGeodToCart(pos2);
355   sgdMat4 ecTrans;
356   sgdMakeCoordMat4(ecTrans, cartPos3D.x(), cartPos3D.y(), cartPos3D.z(),
357                    pos.lon(), 0, - 90 - pos.lat());
358   sgdXformPnt3(sgdOff, ecTrans);
359
360   return Point3D(sgdOff[0], sgdOff[1], sgdOff[2]);
361 }
362
363 Point3D
364 FGAIBase::getGeocPosAt(const Point3D& off) const
365 {
366   return sgCartToGeod(getCartPosAt(off));
367 }
368
369 /*
370  * getters and Setters
371  */
372 void FGAIBase::_setLongitude( double longitude ) {
373     pos.setlon(longitude);
374 }
375 void FGAIBase::_setLatitude ( double latitude )  {
376     pos.setlat(latitude);
377 }
378
379 double FGAIBase::_getLongitude() const {
380     return pos.lon();
381 }
382 double FGAIBase::_getLatitude () const {
383     return pos.lat();
384 }
385 double FGAIBase::_getRdot() const {
386     return rdot;
387 }
388 double FGAIBase::_getVS_fps() const {
389     return vs*60.0;
390 }
391 void FGAIBase::_setVS_fps( double _vs ) {
392     vs = _vs/60.0;
393 }
394
395 double FGAIBase::_getAltitude() const {
396     return altitude;
397 }
398 void FGAIBase::_setAltitude( double _alt ) {
399     setAltitude( _alt );
400 }
401
402 bool FGAIBase::_isNight() {
403     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
404 }
405
406 int FGAIBase::getID() const {
407     return  _refID;
408 }
409
410 void FGAIBase::CalculateMach() {
411      // Calculate rho at altitude, using standard atmosphere
412      // For the temperature T and the pressure p,
413  
414      if (altitude < 36152) {            // curve fits for the troposphere
415        T = 59 - 0.00356 * altitude;
416        p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
417  
418      } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
419        T = -70;
420        p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
421  
422      } else {                                    //  upper stratosphere
423        T = -205.05 + (0.00164 * altitude);
424        p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
425      }
426  
427      rho = p / (1718 * (T + 459.7));
428         
429         // calculate the speed of sound at altitude
430         // a = sqrt ( g * R * (T + 459.7))
431         // where:
432         // a = speed of sound [ft/s]
433         // g = specific heat ratio, which is usually equal to 1.4  
434         // R = specific gas constant, which equals 1716 ft-lb/slug/°R 
435         
436         a = sqrt ( 1.4 * 1716 * (T + 459.7));
437         
438         // calculate Mach number
439         
440         Mach = speed/a;
441         
442  //     cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach;
443 }
444
445 int FGAIBase::_newAIModelID() {
446    static int id = 0;
447    if (!++id) id++;     // id = 0 is not allowed.
448    return id;
449 }
450