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