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