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