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