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