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