]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/wxradar.cxx
Make comparisons against OSG version less flakey
[flightgear.git] / src / Instrumentation / wxradar.cxx
1 // Wx Radar background texture
2 //
3 // Written by Harald JOHNSEN, started May 2005.
4 // With major amendments by Vivian MEAZZA May 2007
5 // Ported to OSG by Tim Moore Jun 2007
6 //
7 //
8 // Copyright (C) 2005  Harald JOHNSEN
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 //
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include <osg/Array>
31 #include <osg/Geometry>
32 #include <osg/Matrixf>
33 #include <osg/PrimitiveSet>
34 #include <osg/StateSet>
35 #include <osg/Version>
36 #include <osgDB/ReaderWriter>
37 #include <osgDB/WriteFile>
38
39 #include <simgear/constants.h>
40 #include <simgear/misc/sg_path.hxx>
41 #include <simgear/environment/visual_enviro.hxx>
42 #include <simgear/scene/model/model.hxx>
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/math/sg_geodesy.hxx>
46
47 #include <sstream>
48 #include <iomanip>
49 SG_USING_STD(stringstream);
50 SG_USING_STD(endl);
51 SG_USING_STD(setprecision);
52 SG_USING_STD(fixed);
53 SG_USING_STD(setw);
54 SG_USING_STD(setfill);
55
56 #include <Main/fg_props.hxx>
57 #include <Main/globals.hxx>
58 #include <Cockpit/panel.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <AIModel/AIBase.hxx>
61 #include <AIModel/AIManager.hxx>
62 #include <AIModel/AIBallistic.hxx>
63
64 #include <Include/general.hxx>
65 #include "instrument_mgr.hxx"
66 #include "od_gauge.hxx"
67 #include "wxradar.hxx"
68
69
70 typedef list <SGSharedPtr<FGAIBase> > radar_list_type;
71 typedef radar_list_type::iterator radar_list_iterator;
72 typedef radar_list_type::const_iterator radar_list_const_iterator;
73
74
75 static const float UNIT = 1.0f / 8.0f;  // 8 symbols in a row/column in the texture
76 static const char *DEFAULT_FONT = "typewriter.txf";
77
78 wxRadarBg::wxRadarBg ( SGPropertyNode *node) :
79     _name(node->getStringValue("name", "radar")),
80     _num(node->getIntValue("number", 0)),
81     _interval(node->getDoubleValue("update-interval-sec", 1.0)),
82     _time( 0.0 ),
83     _last_switchKnob( "off" ),
84     _sim_init_done ( false ),
85     _resultTexture( 0 ),
86     _wxEcho( 0 ),
87     _odg( 0 )
88 {
89     const char *tacan_source = node->getStringValue("tacan-source",
90             "/instrumentation/tacan");
91     _Tacan = fgGetNode(tacan_source, true);
92 }
93
94
95 wxRadarBg::~wxRadarBg ()
96 {
97     if (_radar_font_node != 0) {
98         _radar_font_node->removeChangeListener(this);
99     }
100 }
101
102
103 void
104 wxRadarBg::init ()
105 {
106     string branch;
107     branch = "/instrumentation/" + _name;
108
109     _Instrument = fgGetNode(branch.c_str(), _num, true );
110     _serviceable_node = _Instrument->getNode("serviceable", true);
111
112     // texture name to use in 2D and 3D instruments
113     _texture_path = _Instrument->getStringValue("radar-texture-path",
114             "Aircraft/Instruments/Textures/od_wxradar.rgb");
115     _resultTexture = FGTextureManager::createTexture(_texture_path.c_str());
116
117     SGPath tpath(globals->get_fg_root());
118     string path = _Instrument->getStringValue("echo-texture-path",
119             "Aircraft/Instruments/Textures/wxecho.rgb");
120     tpath.append(path);
121
122     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
123     _wxEcho = SGLoadTexture2D(tpath.c_str(), false, false);
124
125
126     _Instrument->setFloatValue("trk", 0.0);
127     _Instrument->setFloatValue("tilt", 0.0);
128     _Instrument->setStringValue("status","");
129     // those properties are used by a radar instrument of a MFD
130     // input switch = OFF | TST | STBY | ON
131     // input mode = WX | WXA | MAP
132     // output status = STBY | TEST | WX | WXA | MAP | blank
133     // input lightning = true | false
134     // input TRK = +/- n degrees
135     // input TILT = +/- n degree
136     // input autotilt = true | false
137     // input range = n nm (20/40/80)
138     // input display-mode = arc | rose | map | plan
139
140     FGInstrumentMgr *imgr = (FGInstrumentMgr *) globals->get_subsystem("instrumentation");
141     _odg = (FGODGauge *) imgr->get_subsystem("od_gauge");
142     _odg->setSize(512);
143
144     _ai = (FGAIManager*)globals->get_subsystem("ai_model");
145     _ai_enabled_node = fgGetNode("/sim/ai/enabled", true);
146
147     _user_lat_node = fgGetNode("/position/latitude-deg", true);
148     _user_lon_node = fgGetNode("/position/longitude-deg", true);
149     _user_alt_node = fgGetNode("/position/altitude-ft", true);
150
151     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
152     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
153
154     _tacan_serviceable_node = _Tacan->getNode("serviceable", true);
155     _tacan_distance_node    = _Tacan->getNode("indicated-distance-nm", true);
156     _tacan_name_node        = _Tacan->getNode("name", true);
157     _tacan_bearing_node     = _Tacan->getNode("indicated-bearing-true-deg", true);
158     _tacan_in_range_node    = _Tacan->getNode("in-range", true);
159
160     _radar_mode_control_node = _Instrument->getNode("mode-control", true);
161     _radar_coverage_node     = _Instrument->getNode("limit-deg", true);
162     _radar_ref_rng_node      = _Instrument->getNode("reference-range-nm", true);
163     _radar_hdg_marker_node   = _Instrument->getNode("heading-marker", true);
164
165     SGPropertyNode *n = _Instrument->getNode("display-controls", true);
166     _radar_weather_node     = n->getNode("WX", true);
167     _radar_position_node    = n->getNode("pos", true);
168     _radar_data_node        = n->getNode("data", true);
169     _radar_symbol_node      = n->getNode("symbol", true);
170     _radar_centre_node      = n->getNode("centre", true);
171     _radar_rotate_node      = n->getNode("rotate", true);
172     _radar_font_node        = _Instrument->getNode("font", true);
173     _radar_font_node->addChangeListener(this);
174     
175     updateFont();
176
177     _radar_centre_node->setBoolValue(false);
178     if (_radar_coverage_node->getType() == SGPropertyNode::NONE)
179         _radar_coverage_node->setFloatValue(120);
180     if (_radar_ref_rng_node->getType() == SGPropertyNode::NONE)
181         _radar_ref_rng_node->setDoubleValue(35);
182     if (_radar_hdg_marker_node->getType() == SGPropertyNode::NONE)
183         _radar_hdg_marker_node->setBoolValue(true);
184
185     _x_offset = 0;
186     _y_offset = 0;
187
188     // OSG geometry setup. The polygons for the radar returns will be
189     // stored in a single Geometry. The geometry will have several
190     // primitive sets so we can have different kinds of polys and
191     // choose a different overall color for each set.
192     _radarGeode = new osg::Geode;
193     osg::StateSet* stateSet = _radarGeode->getOrCreateStateSet();
194     stateSet->setTextureAttributeAndModes(0, _wxEcho.get());
195     _geom = new osg::Geometry;
196     _geom->setUseDisplayList(false);
197     // Initially allocate space for 128 quads
198     _vertices = new osg::Vec2Array;
199     _vertices->setDataVariance(osg::Object::DYNAMIC);
200     _vertices->reserve(128 * 4);
201     _geom->setVertexArray(_vertices);
202     _texCoords = new osg::Vec2Array;
203     _texCoords->setDataVariance(osg::Object::DYNAMIC);
204     _texCoords->reserve(128 * 4);
205     _geom->setTexCoordArray(0, _texCoords);
206     osg::Vec3Array* colors = new osg::Vec3Array;
207     colors->push_back(osg::Vec3(1.0f, 1.0f, 1.0f)); // color of echos
208     colors->push_back(osg::Vec3(1.0f, 0.0f, 0.0f)); // arc mask
209     colors->push_back(osg::Vec3(0.0f, 0.0f, 0.0f)); // rest of mask
210     _geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
211     _geom->setColorArray(colors);
212     osg::PrimitiveSet* pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
213     pset->setDataVariance(osg::Object::DYNAMIC);
214     _geom->addPrimitiveSet(pset);
215     pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
216     pset->setDataVariance(osg::Object::DYNAMIC);
217     _geom->addPrimitiveSet(pset);
218     pset = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES);
219     pset->setDataVariance(osg::Object::DYNAMIC);
220     _geom->addPrimitiveSet(pset);
221     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
222             osg::Vec3f(256.0f, 256.0f, 0.0f)));
223     _radarGeode->addDrawable(_geom);
224     _odg->allocRT();
225     // Texture in the 2D panel system
226     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
227
228     _textGeode = new osg::Geode;
229
230     osg::Camera* camera = _odg->getCamera();
231     camera->addChild(_radarGeode.get());
232     camera->addChild(_textGeode.get());
233 }
234
235
236 // Local coordinates for each echo
237 const osg::Vec3f echoCoords[4] = {
238     osg::Vec3f(-.7f, -.7f, 0.0f), osg::Vec3f(.7f, -.7f, 0.0f),
239     osg::Vec3f(.7f, .7f, 0.0f), osg::Vec3f(-.7f, .7f, 0.0f)
240 };
241
242
243 const osg::Vec2f echoTexCoords[4] = {
244     osg::Vec2f(0.0f, 0.0f), osg::Vec2f(UNIT, 0.0f),
245     osg::Vec2f(UNIT, UNIT), osg::Vec2f(0.0f, UNIT)
246 };
247
248
249 // helper
250 static void
251 addQuad(osg::Vec2Array* vertices, osg::Vec2Array* texCoords,
252         const osg::Matrixf& transform, const osg::Vec2f& texBase)
253 {
254     for (int i = 0; i < 4; i++) {
255         const osg::Vec3f coords = transform.preMult(echoCoords[i]);
256         texCoords->push_back(texBase + echoTexCoords[i]);
257         vertices->push_back(osg::Vec2f(coords.x(), coords.y()));
258     }
259 }
260
261
262 // Rotate by a heading value
263 static inline
264 osg::Matrixf wxRotate(float angle)
265 {
266     return osg::Matrixf::rotate(angle, 0.0f, 0.0f, -1.0f);
267 }
268
269
270 void
271 wxRadarBg::update (double delta_time_sec)
272 {
273     if ( ! _sim_init_done ) {
274         if ( ! fgGetBool("sim/sceneryloaded", false) )
275             return;
276
277         _sim_init_done = true;
278     }
279     if ( !_odg || ! _serviceable_node->getBoolValue() ) {
280         _Instrument->setStringValue("status","");
281         return;
282     }
283     _time += delta_time_sec;
284     if (_time < _interval)
285         return;
286
287     _time = 0.0;
288
289     string mode = _Instrument->getStringValue("display-mode", "arc");
290     if (mode == "map") {
291         if (_display_mode != MAP) {
292             _display_mode = MAP;
293             center_map();
294         }
295     } else if (mode == "plan") {
296         _display_mode = PLAN;
297     } else {
298         _display_mode = ARC;
299     }
300
301     string switchKnob = _Instrument->getStringValue("switch", "on");
302     if ( _last_switchKnob != switchKnob ) {
303         // since 3D models don't share textures with the rest of the world
304         // we must locate them and replace their handle by hand
305         // only do that when the instrument is turned on
306         //if ( _last_switchKnob == "off" )
307         //_odg->set_texture(_texture_path.c_str(), _resultTexture->getHandle());
308
309         _last_switchKnob = switchKnob;
310     }
311
312     if ( switchKnob == "off" ) {
313         _Instrument->setStringValue("status","");
314     } else if ( switchKnob == "stby" ) {
315         _Instrument->setStringValue("status","STBY");
316     } else if ( switchKnob == "tst" ) {
317         _Instrument->setStringValue("status","TST");
318         // find something interesting to do...
319     } else {
320         float r = _Instrument->getFloatValue("range", 40.0);
321         if (r != _range_nm) {
322             center_map();
323             _range_nm = r;
324         }
325
326         _radar_ref_rng = _radar_ref_rng_node->getDoubleValue();
327         _view_heading = get_heading() * SG_DEGREES_TO_RADIANS;
328         _centerTrans.makeTranslate(0.0f, 0.0f, 0.0f);
329
330         _scale = 200.0 / _range_nm;
331         _angle_offset = 0;
332
333         if ( _display_mode == ARC ) {
334             _scale = 2*200.0f / _range_nm;
335             _angle_offset = -_view_heading;
336             _centerTrans.makeTranslate(0.0f, -200.0f, 0.0f);
337
338         } else if ( _display_mode == MAP ) {
339             apply_map_offset();
340
341             bool centre = _radar_centre_node->getBoolValue();
342             if (centre) {
343                 center_map();
344                 _radar_centre_node->setBoolValue(false);
345             }
346
347             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: displacement "
348             //        << _x_offset <<", "<<_y_offset
349             //        << " user_speed_east_fps * SG_FPS_TO_KT "
350             //        << user_speed_east_fps * SG_FPS_TO_KT
351             //        << " user_speed_north_fps * SG_FPS_TO_KT "
352             //        << user_speed_north_fps * SG_FPS_TO_KT
353             //        << " dt " << delta_time_sec);
354
355             _centerTrans.makeTranslate(_x_offset, _y_offset, 0.0f);
356
357         } else if ( _display_mode == PLAN ) {
358             if (_radar_rotate_node->getBoolValue()) {
359                 _angle_offset = -_view_heading;
360             }
361         } else {
362             // rose
363         }
364
365         _vertices->clear();
366         _texCoords->clear();
367         _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
368
369
370         update_weather();
371
372
373         osg::DrawArrays* quadPSet
374                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(0));
375         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
376         quadPSet->dirty();
377
378         // erase what is out of sight of antenna
379         /*
380             |\     /|
381             | \   / |
382             |  \ /  |
383             ---------
384             |       |
385             |       |
386             ---------
387         */
388
389         osg::DrawArrays* maskPSet
390                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(1));
391         osg::DrawArrays* trimaskPSet
392                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(2));
393
394         if ( _display_mode == ARC ) {
395             float xOffset = 256.0f;
396             float yOffset = 200.0f;
397
398             int firstQuadVert = _vertices->size();
399             _texCoords->push_back(osg::Vec2f(0.5f, 0.25f));
400             _vertices->push_back(osg::Vec2f(-xOffset, 0.0 + yOffset));
401             _texCoords->push_back(osg::Vec2f(1.0f, 0.25f));
402             _vertices->push_back(osg::Vec2f(xOffset, 0.0 + yOffset));
403             _texCoords->push_back(osg::Vec2f(1.0f, 0.5f));
404             _vertices->push_back(osg::Vec2f(xOffset, 256.0 + yOffset));
405             _texCoords->push_back(osg::Vec2f(0.5f, 0.5f));
406             _vertices->push_back(osg::Vec2f(-xOffset, 256.0 + yOffset));
407             maskPSet->set(osg::PrimitiveSet::QUADS, firstQuadVert, 4);
408
409             // The triangles aren't supposed to be textured, but there's
410             // no need to set up a different Geometry, switch modes,
411             // etc. I happen to know that there's a white pixel in the
412             // texture at 1.0, 0.0 :)
413             float centerY = tan(30 * SG_DEGREES_TO_RADIANS);
414             _vertices->push_back(osg::Vec2f(0.0, 0.0));
415             _vertices->push_back(osg::Vec2f(-256.0, 0.0));
416             _vertices->push_back(osg::Vec2f(-256.0, 256.0 * centerY));
417
418             _vertices->push_back(osg::Vec2f(0.0, 0.0));
419             _vertices->push_back(osg::Vec2f(256.0, 0.0));
420             _vertices->push_back(osg::Vec2f(256.0, 256.0 * centerY));
421
422             _vertices->push_back(osg::Vec2f(-256, 0.0));
423             _vertices->push_back(osg::Vec2f(256.0, 0.0));
424             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
425
426             _vertices->push_back(osg::Vec2f(256, 0.0));
427             _vertices->push_back(osg::Vec2f(256.0, -256.0));
428             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
429
430             const osg::Vec2f whiteSpot(1.0f, 0.0f);
431             for (int i = 0; i < 3 * 4; i++)
432                 _texCoords->push_back(whiteSpot);
433
434             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, firstQuadVert + 4,
435                     3 * 4);
436
437         } else {
438             maskPSet->set(osg::PrimitiveSet::QUADS, 0, 0);
439             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, 0, 0);
440         }
441
442         maskPSet->dirty();
443         trimaskPSet->dirty();
444
445         // draw without mask
446         _vertices->clear();
447         _texCoords->clear();
448
449         update_aircraft();
450         update_tacan();
451         update_heading_marker();
452
453         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
454         quadPSet->dirty();
455     }
456 }
457
458
459 void
460 wxRadarBg::update_weather()
461 {
462     string modeButton = _Instrument->getStringValue("mode", "wx");
463     _radarEchoBuffer = *sgEnviro.get_radar_echo();
464
465     // pretend we have a scan angle bigger then the FOV
466     // TODO:check real fov, enlarge if < nn, and do clipping if > mm
467     const float fovFactor = 1.45f;
468     _Instrument->setStringValue("status", modeButton.c_str());
469
470     list_of_SGWxRadarEcho *radarEcho = &_radarEchoBuffer;
471     list_of_SGWxRadarEcho::iterator iradarEcho, end = radarEcho->end();
472     const float LWClevel[] = { 0.1f, 0.5f, 2.1f };
473
474     // draw the cloud radar echo
475     bool drawClouds = _radar_weather_node->getBoolValue();
476     if (drawClouds) {
477
478         // we do that in 3 passes, one for each color level
479         // this is to 'merge' same colors together
480         for (int level = 0; level <= 2; level++) {
481             float col = level * UNIT;
482
483             for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
484                 int cloudId = iradarEcho->cloudId;
485                 bool upgrade = (cloudId >> 5) & 1;
486                 float lwc = iradarEcho->LWC + (upgrade ? 1.0f : 0.0f);
487
488                 // skip ns
489                 if (iradarEcho->LWC >= 0.5 && iradarEcho->LWC <= 0.6)
490                     continue;
491
492                 if (iradarEcho->lightning || lwc < LWClevel[level])
493                     continue;
494
495                 float radius = sgSqrt(iradarEcho->dist) * SG_METER_TO_NM * _scale;
496                 float size = iradarEcho->radius * 2.0 * SG_METER_TO_NM * _scale;
497
498                 if (radius - size > 180)
499                     continue;
500
501                 float angle = (iradarEcho->heading - _angle_offset) //* fovFactor
502                         + 0.5 * SG_PI;
503
504                 // Rotate echo into position, and rotate echo to have
505                 // a constant orientation towards the
506                 // airplane. Compass headings increase in clockwise
507                 // direction, while graphics rotations follow
508                 // right-hand (counter-clockwise) rule.
509                 const osg::Vec2f texBase(col, (UNIT * (float) (4 + (cloudId & 3))));
510
511                 osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
512                         * osg::Matrixf::translate(0.0f, radius, 0.0f)
513                         * wxRotate(angle) * _centerTrans);
514                 addQuad(_vertices, _texCoords, m, texBase);
515
516                 //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: drawing clouds"
517                 //        << " ID=" << cloudId
518                 //        << " x=" << x
519                 //        << " y="<< y
520                 //        << " radius=" << radius
521                 //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
522                 //        << " heading=" << iradarEcho->heading * SG_RADIANS_TO_DEGREES
523                 //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
524             }
525         }
526     }
527
528     // draw lightning echos
529     bool drawLightning = _Instrument->getBoolValue("lightning", true);
530     if ( drawLightning ) {
531         const osg::Vec2f texBase(3 * UNIT, 4 * UNIT);
532
533         for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
534             if (!iradarEcho->lightning)
535                 continue;
536
537             float size = UNIT * 0.5f;
538             float radius = iradarEcho->dist * _scale;
539             float angle = iradarEcho->heading * SG_DEGREES_TO_RADIANS
540                     - _angle_offset;
541
542             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
543                     * wxRotate(-angle)
544                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
545                     * wxRotate(angle) * _centerTrans);
546             addQuad(_vertices, _texCoords, m, texBase);
547         }
548     }
549 }
550
551 void
552 wxRadarBg::update_data(FGAIBase* ac, double radius, double bearing, bool selected)
553 {
554     osgText::Text* callsign = new osgText::Text;
555     callsign->setFont(_font.get());
556     callsign->setFontResolution(12, 12);
557     callsign->setCharacterSize(12);
558     callsign->setColor(selected ? osg::Vec4(1, 1, 1, 1) : osg::Vec4(0, 1, 0, 1));
559     osg::Matrixf m(wxRotate(-bearing)
560             * osg::Matrixf::translate(0.0f, radius, 0.0f)
561             * wxRotate(bearing) * _centerTrans);
562
563     osg::Vec3 pos = m.preMult(osg::Vec3(16, 16, 0));
564     // cast to int's, otherwise text comes out ugly
565     callsign->setPosition(osg::Vec3((int)pos.x(), (int)pos.y(), 0));
566     callsign->setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE);
567     callsign->setLineSpacing(0.25);
568                         
569     stringstream text;
570     text << ac->_getCallsign() << endl 
571         << setprecision(0) << fixed
572         << setw(3) << setfill('0') << ac->_getHeading() << "\xB0 "
573         << setw(0) << ac->_getAltitude() << "ft" << endl
574         << ac->_getSpeed() << "kts";
575
576     callsign->setText(text.str());
577     _textGeode->addDrawable(callsign);
578 }
579
580 void
581 wxRadarBg::update_aircraft()
582 {
583     if (!_ai_enabled_node->getBoolValue())
584         return;
585
586     bool draw_echoes = _radar_position_node->getBoolValue();
587     bool draw_symbols = _radar_symbol_node->getBoolValue();
588     bool draw_data = _radar_data_node->getBoolValue();
589     if (!draw_echoes && !draw_symbols && !draw_data)
590         return;
591
592     radar_list_type radar_list = _ai->get_ai_list();
593     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: AI submodel list size" << radar_list.size());
594     if (radar_list.empty())
595         return;
596
597     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: Loading AI submodels ");
598     const double echo_radii[] = {0, 1, 1.5, 1.5, 0.001, 0.1, 1.5, 2, 1.5, 1.5};
599
600     double user_lat = _user_lat_node->getDoubleValue();
601     double user_lon = _user_lon_node->getDoubleValue();
602     double user_alt = _user_alt_node->getDoubleValue();
603
604     float limit = _radar_coverage_node->getFloatValue();
605     if (limit > 180)
606         limit = 180;
607     else if (limit < 0)
608         limit = 0;
609     limit *= SG_DEGREES_TO_RADIANS;
610
611     radar_list_iterator it = radar_list.begin();
612     radar_list_iterator end = radar_list.end();
613     FGAIBase *selected_ac = 0;
614     double selected_radius = 0;
615     double selected_bearing = 0;
616     int selected_id = fgGetInt("/instrumentation/radar/selected-id", -1);
617
618     for (; it != end; ++it) {
619         FGAIBase *ac = *it;
620         int type       = ac->getType();
621         double lat     = ac->_getLatitude();
622         double lon     = ac->_getLongitude();
623         double alt     = ac->_getAltitude();
624         double heading = ac->_getHeading();
625
626         double range, bearing;
627         calcRangeBearing(user_lat, user_lon, lat, lon, range, bearing);
628
629         //SG_LOG(SG_GENERAL, SG_DEBUG,
630         //        "Radar: ID=" << ac->getID() << "(" << radar_list.size() << ")"
631         //        << " type=" << type
632         //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
633         //        << " alt=" << alt
634         //        << " heading=" << heading
635         //        << " range=" << range
636         //        << " bearing=" << bearing);
637
638         bool isVisible = withinRadarHorizon(user_alt, alt, range);
639         SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: visible " << isVisible);
640         if (!isVisible)
641             continue;
642
643         if (!inRadarRange(type, range))
644             continue;
645
646         bearing *= SG_DEGREES_TO_RADIANS;
647         heading *= SG_DEGREES_TO_RADIANS;
648
649         float radius = range * _scale;
650         float angle = calcRelBearing(bearing, _view_heading);
651
652         if (angle > limit || angle < -limit)
653             continue;
654
655         bearing += _angle_offset;
656         heading += _angle_offset;
657
658         // pos mode
659         if (draw_echoes) {
660             float echo_radius = echo_radii[type] * 120;
661             float size = echo_radius * UNIT;
662
663             const osg::Vec2f texBase(3 * UNIT, 3 * UNIT);
664             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
665                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
666                     * wxRotate(bearing) * _centerTrans);
667             addQuad(_vertices, _texCoords, m, texBase);
668
669             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing AI"
670             //        << " x=" << x << " y=" << y
671             //        << " radius=" << radius
672             //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
673         }
674
675         // data mode
676         if (draw_symbols) {
677             const osg::Vec2f texBase(0, 3 * UNIT);
678             float size = 600 * UNIT;
679             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
680                     * wxRotate(heading - bearing)
681                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
682                     * wxRotate(bearing) * _centerTrans);
683             addQuad(_vertices, _texCoords, m, texBase);
684
685             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing data"
686             //        << " x=" << x <<" y="<< y
687             //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
688             //        << " radius=" << radius);
689         }
690         
691         if (draw_data) {
692             if (ac->getID() == selected_id) {
693                 selected_ac = ac;
694                 selected_radius = radius;
695                 selected_bearing = bearing;
696             } else {
697                 update_data(ac, radius, bearing, false);
698             }
699         }
700     }
701     if (selected_ac) {
702         update_data(selected_ac, selected_radius, selected_bearing, true);
703     }
704 }
705
706
707 void
708 wxRadarBg::update_tacan()
709 {
710     // draw TACAN symbol
711     int mode = _radar_mode_control_node->getIntValue();
712     bool inRange = _tacan_in_range_node->getBoolValue();
713
714     if (mode != 1 || !inRange)
715         return;
716
717     float size = 600 * UNIT;
718     float radius = _tacan_distance_node->getFloatValue() * _scale;
719     float angle = _tacan_bearing_node->getFloatValue() * SG_DEGREES_TO_RADIANS
720             + _angle_offset;
721
722     const osg::Vec2f texBase(1 * UNIT, 3 * UNIT);
723     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
724             * wxRotate(-angle)
725             * osg::Matrixf::translate(0.0f, radius, 0.0f)
726             * wxRotate(angle) * _centerTrans);
727     addQuad(_vertices, _texCoords, m, texBase);
728
729     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:     drawing TACAN"
730     //        << " dist=" << radius
731     //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
732     //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
733     //        << " x=" << x << " y="<< y
734     //        << " size=" << size);
735 }
736
737
738 void
739 wxRadarBg::update_heading_marker()
740 {
741     if (!_radar_hdg_marker_node->getBoolValue())
742         return;
743
744     const osg::Vec2f texBase(2 * UNIT, 3 * UNIT);
745     float size = 600 * UNIT;
746     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
747             * wxRotate(_view_heading + _angle_offset));
748
749     m *= _centerTrans;
750     addQuad(_vertices, _texCoords, m, texBase);
751
752     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:   drawing heading marker"
753     //        << " x,y " << x <<","<< y
754     //        << " dist" << dist
755     //        << " view_heading" << _view_heading * SG_RADIANS_TO_DEGREES
756     //        << " heading " << iradarEcho->heading * SG_RADIANS_TO_DEGREES
757     //        << " angle " << angle * SG_RADIANS_TO_DEGREES);
758 }
759
760
761 void
762 wxRadarBg::center_map()
763 {
764     _lat = _user_lat_node->getDoubleValue();
765     _lon = _user_lon_node->getDoubleValue();
766     _x_offset = _y_offset = 0;
767 }
768
769
770 void
771 wxRadarBg::apply_map_offset()
772 {
773     double lat = _user_lat_node->getDoubleValue();
774     double lon = _user_lon_node->getDoubleValue();
775     double bearing, distance, az2;
776     geo_inverse_wgs_84(_lat, _lon, lat, lon, &bearing, &az2, &distance);
777     distance *= SG_METER_TO_NM * _scale;
778     bearing *= SG_DEGREES_TO_RADIANS;
779     _x_offset += sin(bearing) * distance;
780     _y_offset += cos(bearing) * distance;
781     _lat = lat;
782     _lon = lon;
783 }
784
785
786 bool
787 wxRadarBg::withinRadarHorizon(double user_alt, double alt, double range_nm)
788 {
789     // Radar Horizon  = 1.23(ht^1/2 + hr^1/2),
790     //don't allow negative altitudes (an approximation - yes altitudes can be negative)
791
792     if (user_alt < 0)
793         user_alt = 0;
794
795     if (alt < 0)
796         alt = 0;
797
798     double radarhorizon = 1.23 * (sqrt(alt) + sqrt(user_alt));
799     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: horizon " << radarhorizon);
800     return radarhorizon >= range_nm;
801 }
802
803
804 bool
805 wxRadarBg::inRadarRange(int type, double range_nm)
806 {
807     //The Radar Equation:
808     //
809     // MaxRange^4 = (TxPower * AntGain^2 * lambda^2 * sigma)/((constant) * MDS)
810     //
811     // Where (constant) = (4*pi)3 and MDS is the Minimum Detectable Signal power.
812     //
813     // For a given radar we can assume that the only variable is sigma,
814     // the target radar cross section.
815     //
816     // Here, we will use a normalised rcs (sigma) for a standard taget and assume that this
817     // will provide a maximum range of 35nm;
818     //
819     // TODO - make the maximum range adjustable at runtime
820
821     const double sigma[] = {0, 1, 100, 100, 0.001, 0.1, 100, 100, 1, 1};
822     double constant = _radar_ref_rng;
823
824     if (constant <= 0)
825         constant = 35;
826
827     double maxrange = constant * pow(sigma[type], 0.25);
828     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: max range " << maxrange);
829     return maxrange >= range_nm;
830 }
831
832
833 void
834 wxRadarBg::calcRangeBearing(double lat, double lon, double lat2, double lon2,
835         double &range, double &bearing ) const
836 {
837     // calculate the bearing and range of the second pos from the first
838     double az2, distance;
839     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
840     range = distance *= SG_METER_TO_NM;
841 }
842
843
844 float
845 wxRadarBg::calcRelBearing(float bearing, float heading)
846 {
847     float angle = bearing - heading;
848
849     if (angle >= SG_PI)
850         angle -= 2.0 * SG_PI;
851
852     if (angle < -SG_PI)
853         angle += 2.0 * SG_PI;
854
855     return angle;
856 }
857
858 void
859 wxRadarBg::updateFont()
860 {
861     SGPath tpath;
862     string path = _radar_font_node->getStringValue();
863     if (path.length() == 0) {
864         path = DEFAULT_FONT;
865     }
866     if (path[0] != '/') {
867         tpath = globals->get_fg_root();
868         tpath.append("Fonts");
869         tpath.append(path);
870     } else {
871         tpath = path;
872     }
873 #if (FG_OSG_VERSION >= 21000)
874     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
875     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());    
876 #else    
877     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str());
878 #endif
879     if (font != 0) {
880         _font = font;
881         _font->setMinFilterHint(osg::Texture::NEAREST);
882         _font->setMagFilterHint(osg::Texture::NEAREST);
883         _font->setGlyphImageMargin(0);
884         _font->setGlyphImageMarginRatio(0);
885     }
886 }
887
888 void
889 wxRadarBg::valueChanged(SGPropertyNode*)
890 {
891     updateFont();
892 }