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