]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/wxradar.cxx
ae1aeb845716fab4729296cfa8b2933909313f18
[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 <osgDB/WriteFile>
36
37 #include <simgear/constants.h>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/environment/visual_enviro.hxx>
40 #include <simgear/scene/model/model.hxx>
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/math/sg_geodesy.hxx>
44
45 #include <Main/fg_props.hxx>
46 #include <Main/globals.hxx>
47 #include <Cockpit/panel.hxx>
48 #include <Cockpit/hud.hxx>
49 #include <AIModel/AIBase.hxx>
50 #include <AIModel/AIManager.hxx>
51 #include <AIModel/AIBallistic.hxx>
52
53 #include "instrument_mgr.hxx"
54 #include "od_gauge.hxx"
55 #include "wxradar.hxx"
56
57
58 typedef list <SGSharedPtr<FGAIBase> > radar_list_type;
59 typedef radar_list_type::iterator radar_list_iterator;
60 typedef radar_list_type::const_iterator radar_list_const_iterator;
61
62
63 // texture name to use in 2D and 3D instruments
64 static const char *ODGAUGE_NAME = "Aircraft/Instruments/Textures/od_wxradar.rgb";
65 static const float UNIT = 1.0f / 8.0f;  // 8 symbols in a row/column in the texture
66
67
68 wxRadarBg::wxRadarBg ( SGPropertyNode *node) :
69     _name(node->getStringValue("name", "radar")),
70     _num(node->getIntValue("number", 0)),
71     _interval(node->getDoubleValue("update-interval-sec", 1.0)),
72     _time( 0.0 ),
73     _last_switchKnob( "off" ),
74     _sim_init_done ( false ),
75     _resultTexture( 0 ),
76     _wxEcho( 0 ),
77     _odg( 0 )
78 {
79     const char *tacan_source = node->getStringValue("tacan-source",
80             "/instrumentation/tacan");
81     _Tacan = fgGetNode(tacan_source, true);
82 }
83
84
85 wxRadarBg::~wxRadarBg ()
86 {
87 }
88
89
90 void
91 wxRadarBg::init ()
92 {
93     string branch;
94     branch = "/instrumentation/" + _name;
95
96     _Instrument = fgGetNode(branch.c_str(), _num, true );
97     _serviceable_node = _Instrument->getNode("serviceable", true);
98     _resultTexture = FGTextureManager::createTexture( ODGAUGE_NAME );
99
100     SGPath tpath(globals->get_fg_root());
101     string path = _Instrument->getStringValue("echo-texture-path",
102             "Aircraft/Instruments/Textures/wxecho.rgb");
103     tpath.append(path);
104
105     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
106     _wxEcho = SGLoadTexture2D(tpath.c_str(), false, false);
107
108     _Instrument->setFloatValue("trk", 0.0);
109     _Instrument->setFloatValue("tilt", 0.0);
110     _Instrument->setStringValue("status","");
111     // those properties are used by a radar instrument of a MFD
112     // input switch = OFF | TST | STBY | ON
113     // input mode = WX | WXA | MAP
114     // output status = STBY | TEST | WX | WXA | MAP | blank
115     // input lightning = true | false
116     // input TRK = +/- n degrees
117     // input TILT = +/- n degree
118     // input autotilt = true | false
119     // input range = n nm (20/40/80)
120     // input display-mode = arc | rose | map | plan
121
122     FGInstrumentMgr *imgr = (FGInstrumentMgr *) globals->get_subsystem("instrumentation");
123     _odg = (FGODGauge *) imgr->get_subsystem("od_gauge");
124     _odg->setSize(256);
125
126     _ai = (FGAIManager*)globals->get_subsystem("ai_model");
127     _ai_enabled_node = fgGetNode("/sim/ai/enabled", true);
128
129     _user_lat_node = fgGetNode("/position/latitude-deg", true);
130     _user_lon_node = fgGetNode("/position/longitude-deg", true);
131     _user_alt_node = fgGetNode("/position/altitude-ft", true);
132
133     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
134     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
135
136     _tacan_serviceable_node = _Tacan->getNode("serviceable", true);
137     _tacan_distance_node    = _Tacan->getNode("indicated-distance-nm", true);
138     _tacan_name_node        = _Tacan->getNode("name", true);
139     _tacan_bearing_node     = _Tacan->getNode("indicated-bearing-true-deg", true);
140     _tacan_in_range_node    = _Tacan->getNode("in-range", true);
141
142     _radar_mode_control_node = _Instrument->getNode("mode-control", true);
143     _radar_coverage_node     = _Instrument->getNode("limit-deg", true);
144     _radar_ref_rng_node      = _Instrument->getNode("reference-range-nm", true);
145
146     SGPropertyNode *n = _Instrument->getNode("display-controls", true);
147     _radar_weather_node     = n->getNode("WX", true);
148     _radar_position_node    = n->getNode("pos", true);
149     _radar_data_node        = n->getNode("data", true);
150     _radar_centre_node      = n->getNode("centre", true);
151
152     _radar_centre_node->setBoolValue(false);
153     if (_radar_coverage_node->getType() == SGPropertyNode::NONE)
154         _radar_coverage_node->setFloatValue(120);
155     if (_radar_ref_rng_node->getType() == SGPropertyNode::NONE)
156         _radar_ref_rng_node->setDoubleValue(35);
157
158     _x_offset = 0;
159     _y_offset = 0;
160
161     // OSG geometry setup. The polygons for the radar returns will be
162     // stored in a single Geometry. The geometry will have several
163     // primitive sets so we can have different kinds of polys and
164     // choose a different overall color for each set.
165     _radarGeode = new osg::Geode;
166     osg::StateSet* stateSet = _radarGeode->getOrCreateStateSet();
167     stateSet->setTextureAttributeAndModes(0, _wxEcho.get());
168     osg::Geometry* geom = new osg::Geometry;
169     geom->setUseDisplayList(false);
170     // Initially allocate space for 128 quads
171     osg::Vec2Array* vertices = new osg::Vec2Array;
172     vertices->setDataVariance(osg::Object::DYNAMIC);
173     vertices->reserve(128 * 4);
174     geom->setVertexArray(vertices);
175     osg::Vec2Array* texCoords = new osg::Vec2Array;
176     texCoords->setDataVariance(osg::Object::DYNAMIC);
177     texCoords->reserve(128 * 4);
178     geom->setTexCoordArray(0, texCoords);
179     osg::Vec3Array* colors = new osg::Vec3Array;
180     colors->push_back(osg::Vec3(1.0f, 1.0f, 1.0f)); // color of echos
181     colors->push_back(osg::Vec3(1.0f, 0.0f, 0.0f)); // arc mask
182     colors->push_back(osg::Vec3(0.0f, 0.0f, 0.0f)); // rest of mask
183     geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
184     geom->setColorArray(colors);
185     osg::PrimitiveSet* pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
186     pset->setDataVariance(osg::Object::DYNAMIC);
187     geom->addPrimitiveSet(pset);
188     pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
189     pset->setDataVariance(osg::Object::DYNAMIC);
190     geom->addPrimitiveSet(pset);
191     pset = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES);
192     pset->setDataVariance(osg::Object::DYNAMIC);
193     geom->addPrimitiveSet(pset);
194     geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
195             osg::Vec3f(256.0f, 256.0f, 0.0f)));
196     _radarGeode->addDrawable(geom);
197     _odg->allocRT();
198     // Texture in the 2D panel system
199     FGTextureManager::addTexture(ODGAUGE_NAME, _odg->getTexture());
200
201     osg::Camera* camera = _odg->getCamera();
202     camera->addChild(_radarGeode.get());
203
204     _geom = static_cast<osg::Geometry*>(_radarGeode->getDrawable(0));
205     _vertices = static_cast<osg::Vec2Array*>(_geom->getVertexArray());
206     _texCoords = static_cast<osg::Vec2Array*>(_geom->getTexCoordArray(0));
207 }
208
209
210 // Local coordinates for each echo
211 const osg::Vec3f echoCoords[4] = {
212     osg::Vec3f(-.7f, -.7f, 0.0f), osg::Vec3f(.7f, -.7f, 0.0f),
213     osg::Vec3f(.7f, .7f, 0.0f), osg::Vec3f(-.7f, .7f, 0.0f)
214 };
215
216
217 const osg::Vec2f echoTexCoords[4] = {
218     osg::Vec2f(0.0f, 0.0f), osg::Vec2f(UNIT, 0.0f),
219     osg::Vec2f(UNIT, UNIT), osg::Vec2f(0.0f, UNIT)
220 };
221
222
223 // helper
224 static void
225 addQuad(osg::Vec2Array* vertices, osg::Vec2Array* texCoords,
226         const osg::Matrixf& transform, const osg::Vec2f& texBase)
227 {
228     for (int i = 0; i < 4; i++) {
229         const osg::Vec3f coords = transform.preMult(echoCoords[i]);
230         texCoords->push_back(texBase + echoTexCoords[i]);
231         vertices->push_back(osg::Vec2f(coords.x(), coords.y()));
232     }
233 }
234
235
236 // Rotate by a heading value
237 static inline
238 osg::Matrixf wxRotate(float angle)
239 {
240     return osg::Matrixf::rotate(angle, 0.0f, 0.0f, -1.0f);
241 }
242
243
244 void
245 wxRadarBg::update (double delta_time_sec)
246 {
247     if ( ! _sim_init_done ) {
248         if ( ! fgGetBool("sim/sceneryloaded", false) )
249             return;
250
251         _sim_init_done = true;
252     }
253     if ( !_odg || ! _serviceable_node->getBoolValue() ) {
254         _Instrument->setStringValue("status","");
255         return;
256     }
257     _time += delta_time_sec;
258     if (_time < _interval)
259         return;
260
261     _time = 0.0;
262
263     string mode = _Instrument->getStringValue("display-mode", "arc");
264     if (mode == "map") {
265         if (_display_mode != MAP) {
266             _display_mode = MAP;
267             center_map();
268         }
269     } else if (mode == "plan") {
270         _display_mode = PLAN;
271     } else {
272         _display_mode = ARC;
273     }
274
275     string switchKnob = _Instrument->getStringValue("switch", "on");
276     if ( _last_switchKnob != switchKnob ) {
277         // since 3D models don't share textures with the rest of the world
278         // we must locate them and replace their handle by hand
279         // only do that when the instrument is turned on
280         //if ( _last_switchKnob == "off" )
281         //_odg->set_texture( ODGAUGE_NAME, _resultTexture->getHandle());
282         _last_switchKnob = switchKnob;
283     }
284
285     if ( switchKnob == "off" ) {
286         _Instrument->setStringValue("status","");
287     } else if ( switchKnob == "stby" ) {
288         _Instrument->setStringValue("status","STBY");
289     } else if ( switchKnob == "tst" ) {
290         _Instrument->setStringValue("status","TST");
291         // find something interesting to do...
292     } else {
293         float r = _Instrument->getFloatValue("range", 40.0);
294         if (r != _range_nm) {
295             center_map();
296             _range_nm = r;
297         }
298
299         _radar_ref_rng = _radar_ref_rng_node->getDoubleValue();
300         _view_heading = get_heading() * SG_DEGREES_TO_RADIANS;
301         _centerTrans.makeTranslate(0.0f, 0.0f, 0.0f);
302
303         _scale = 200.0 / _range_nm;
304         _angle_offset = 0;
305
306         if ( _display_mode == ARC ) {
307             _scale = 2*200.0f / _range_nm;
308             _angle_offset = -_view_heading;
309             _centerTrans.makeTranslate(0.0f, -200.0f, 0.0f);
310
311         } else if ( _display_mode == MAP ) {
312             apply_map_offset();
313
314             bool centre = _radar_centre_node->getBoolValue();
315             if (centre) {
316                 center_map();
317                 _radar_centre_node->setBoolValue(false);
318             }
319
320             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: displacement "
321             //        << _x_offset <<", "<<_y_offset
322             //        << " user_speed_east_fps * SG_FPS_TO_KT "
323             //        << user_speed_east_fps * SG_FPS_TO_KT
324             //        << " user_speed_north_fps * SG_FPS_TO_KT "
325             //        << user_speed_north_fps * SG_FPS_TO_KT
326             //        << " dt " << delta_time_sec);
327
328             _centerTrans.makeTranslate(_x_offset, _y_offset, 0.0f);
329
330         } else if ( _display_mode == PLAN ) {
331             // no sense I presume
332         } else {
333             // rose
334         }
335
336         _vertices->clear();
337         _texCoords->clear();
338
339
340         update_weather();
341
342
343         osg::DrawArrays* quadPSet
344                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(0));
345         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
346         quadPSet->dirty();
347
348         // erase what is out of sight of antenna
349         /*
350             |\     /|
351             | \   / |
352             |  \ /  |
353             ---------
354             |       |
355             |       |
356             ---------
357         */
358
359         osg::DrawArrays* maskPSet
360                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(1));
361         osg::DrawArrays* trimaskPSet
362                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(2));
363
364         if ( _display_mode == ARC ) {
365             float xOffset = 256.0f;
366             float yOffset = 200.0f;
367
368             int firstQuadVert = _vertices->size();
369             _texCoords->push_back(osg::Vec2f(0.5f, 0.25f));
370             _vertices->push_back(osg::Vec2f(-xOffset, 0.0 + yOffset));
371             _texCoords->push_back(osg::Vec2f(1.0f, 0.25f));
372             _vertices->push_back(osg::Vec2f(xOffset, 0.0 + yOffset));
373             _texCoords->push_back(osg::Vec2f(1.0f, 0.5f));
374             _vertices->push_back(osg::Vec2f(xOffset, 256.0 + yOffset));
375             _texCoords->push_back(osg::Vec2f(0.5f, 0.5f));
376             _vertices->push_back(osg::Vec2f(-xOffset, 256.0 + yOffset));
377             maskPSet->set(osg::PrimitiveSet::QUADS, firstQuadVert, 4);
378             // The triangles aren't supposed to be textured, but there's
379             // no need to set up a different Geometry, switch modes,
380             // etc. I happen to know that there's a white pixel in the
381             // texture at 1.0, 0.0 :)
382             float centerY = tan(30 * SG_DEGREES_TO_RADIANS);
383             const osg::Vec2f whiteSpot(1.0f, 0.0f);
384             _vertices->push_back(osg::Vec2f(0.0, 0.0));
385             _vertices->push_back(osg::Vec2f(-256.0, 0.0));
386             _vertices->push_back(osg::Vec2f(-256.0, 256.0 * centerY));
387
388             _vertices->push_back(osg::Vec2f(0.0, 0.0));
389             _vertices->push_back(osg::Vec2f(256.0, 0.0));
390             _vertices->push_back(osg::Vec2f(256.0, 256.0 * centerY));
391
392             _vertices->push_back(osg::Vec2f(-256, 0.0));
393             _vertices->push_back(osg::Vec2f(256.0, 0.0));
394             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
395
396             _vertices->push_back(osg::Vec2f(256, 0.0));
397             _vertices->push_back(osg::Vec2f(256.0, -256.0));
398             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
399
400             for (int i = 0; i < 3 * 4; i++)
401                 _texCoords->push_back(whiteSpot);
402
403             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, firstQuadVert + 4,
404                     3 * 4);
405
406         } else {
407             maskPSet->set(osg::PrimitiveSet::QUADS, 0, 0);
408             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, 0, 0);
409         }
410
411         maskPSet->dirty();
412         trimaskPSet->dirty();
413
414         // draw without mask
415         _vertices->clear();
416         _texCoords->clear();
417
418         update_aircraft();
419         update_tacan();
420         update_heading_marker();
421
422         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
423         quadPSet->dirty();
424     }
425 }
426
427
428 void
429 wxRadarBg::update_weather()
430 {
431     string modeButton = _Instrument->getStringValue("mode", "wx");
432     _radarEchoBuffer = *sgEnviro.get_radar_echo();
433
434     // pretend we have a scan angle bigger then the FOV
435     // TODO:check real fov, enlarge if < nn, and do clipping if > mm
436     const float fovFactor = 1.45f;
437     _Instrument->setStringValue("status", modeButton.c_str());
438
439     list_of_SGWxRadarEcho *radarEcho = &_radarEchoBuffer;
440     list_of_SGWxRadarEcho::iterator iradarEcho, end = radarEcho->end();
441     const float LWClevel[] = { 0.1f, 0.5f, 2.1f };
442
443     // draw the cloud radar echo
444     bool drawClouds = _radar_weather_node->getBoolValue();
445     if (drawClouds) {
446
447         // we do that in 3 passes, one for each color level
448         // this is to 'merge' same colors together
449         for (int level = 0; level <= 2; level++) {
450             float col = level * UNIT;
451
452             for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
453                 int cloudId = iradarEcho->cloudId;
454                 bool upgrade = (cloudId >> 5) & 1;
455                 float lwc = iradarEcho->LWC + (upgrade ? 1.0f : 0.0f);
456
457                 // skip ns
458                 if (iradarEcho->LWC >= 0.5 && iradarEcho->LWC <= 0.6)
459                     continue;
460
461                 if (iradarEcho->lightning || lwc < LWClevel[level])
462                     continue;
463
464                 float radius = sgSqrt(iradarEcho->dist) * SG_METER_TO_NM * _scale;
465                 float size = iradarEcho->radius * 2.0 * SG_METER_TO_NM * _scale;
466
467                 if (radius - size > 180)
468                     continue;
469
470                 float angle = (iradarEcho->heading - _angle_offset) //* fovFactor
471                         + 0.5 * SG_PI;
472
473                 // Rotate echo into position, and rotate echo to have
474                 // a constant orientation towards the
475                 // airplane. Compass headings increase in clockwise
476                 // direction, while graphics rotations follow
477                 // right-hand (counter-clockwise) rule.
478                 const osg::Vec2f texBase(col, (UNIT * (float) (4 + (cloudId & 3))));
479
480                 osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
481                         * osg::Matrixf::translate(0.0f, radius, 0.0f)
482                         * wxRotate(angle) * _centerTrans);
483                 addQuad(_vertices, _texCoords, m, texBase);
484
485                 //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: drawing clouds"
486                 //        << " ID=" << cloudId
487                 //        << " x=" << x
488                 //        << " y="<< y
489                 //        << " radius=" << radius
490                 //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
491                 //        << " heading=" << iradarEcho->heading * SG_RADIANS_TO_DEGREES
492                 //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
493             }
494         }
495     }
496
497     // draw lightning echos
498     bool drawLightning = _Instrument->getBoolValue("lightning", true);
499     if ( drawLightning ) {
500         const osg::Vec2f texBase(3 * UNIT, 4 * UNIT);
501
502         for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
503             if (!iradarEcho->lightning)
504                 continue;
505
506             float size = UNIT * 0.5f;
507             float radius = iradarEcho->dist * _scale;
508             float angle = iradarEcho->heading * SG_DEGREES_TO_RADIANS
509                     - _angle_offset;
510
511             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
512                     * wxRotate(-angle)
513                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
514                     * wxRotate(angle) * _centerTrans);
515             addQuad(_vertices, _texCoords, m, texBase);
516         }
517     }
518 }
519
520
521 void
522 wxRadarBg::update_aircraft()
523 {
524     if (!_ai_enabled_node->getBoolValue())
525         return;
526
527     bool draw_echoes = _radar_position_node->getBoolValue();
528     bool draw_symbols = _radar_data_node->getBoolValue();
529     if (!draw_echoes && !draw_symbols)
530         return;
531
532     radar_list_type radar_list = _ai->get_ai_list();
533     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: AI submodel list size" << radar_list.size());
534     if (radar_list.empty())
535         return;
536
537     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: Loading AI submodels ");
538     const double echo_radii[] = {0, 1, 1.5, 1.5, 0.001, 0.1, 1.5, 2, 1.5, 1.5};
539
540     double user_lat = _user_lat_node->getDoubleValue();
541     double user_lon = _user_lon_node->getDoubleValue();
542     double user_alt = _user_alt_node->getDoubleValue();
543
544     radar_list_iterator it = radar_list.begin();
545     radar_list_iterator end = radar_list.end();
546
547     for (; it != end; ++it) {
548         FGAIBase *ac = *it;
549         int type       = ac->getType();
550         double lat     = ac->_getLatitude();
551         double lon     = ac->_getLongitude();
552         double alt     = ac->_getAltitude();
553         double heading = ac->_getHeading();
554
555         double range, bearing;
556         calcRangeBearing(user_lat, user_lon, lat, lon, range, bearing);
557
558         //SG_LOG(SG_GENERAL, SG_DEBUG,
559         //        "Radar: ID=" << ac->getID() << "(" << radar_list.size() << ")"
560         //        << " type=" << type
561         //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
562         //        << " alt=" << alt
563         //        << " heading=" << heading
564         //        << " range=" << range
565         //        << " bearing=" << bearing);
566
567         bool isVisible = withinRadarHorizon(user_alt, alt, range);
568         SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: visible " << isVisible);
569         if (!isVisible)
570             continue;
571
572         if (!inRadarRange(type, range))
573             continue;
574
575         bearing *= SG_DEGREES_TO_RADIANS;
576         heading *= SG_DEGREES_TO_RADIANS;
577
578         float radius = range * _scale;
579         float angle = calcRelBearing(bearing, _view_heading);
580
581         float limit = _radar_coverage_node->getFloatValue();
582         if (limit > 180)
583             limit = 180;
584         else if (limit < 0)
585             limit = 0;
586         limit *= SG_DEGREES_TO_RADIANS;
587         if (angle > limit || angle < -limit)
588             continue;
589
590         bearing += _angle_offset;
591         heading += _angle_offset;
592
593         // pos mode
594         if (draw_echoes) {
595             float echo_radius = echo_radii[type] * 120;
596             float size = echo_radius * UNIT;
597
598             const osg::Vec2f texBase(3 * UNIT, 3 * UNIT);
599             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
600                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
601                     * wxRotate(bearing) * _centerTrans);
602             addQuad(_vertices, _texCoords, m, texBase);
603
604             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing AI"
605             //        << " x=" << x << " y=" << y
606             //        << " radius=" << radius
607             //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
608         }
609
610         // data mode
611         if (draw_symbols) {
612             const osg::Vec2f texBase(0, 3 * UNIT);
613             float size = 600 * UNIT;
614             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
615                     * wxRotate(heading - bearing)
616                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
617                     * wxRotate(bearing) * _centerTrans);
618             addQuad(_vertices, _texCoords, m, texBase);
619
620             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing data"
621             //        << " x=" << x <<" y="<< y
622             //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
623             //        << " radius=" << radius);
624         }
625     }
626 }
627
628
629 void
630 wxRadarBg::update_tacan()
631 {
632     // draw TACAN symbol
633     int mode = _radar_mode_control_node->getIntValue();
634     bool inRange = _tacan_in_range_node->getBoolValue();
635
636     if (mode != 1 || !inRange)
637         return;
638
639     float size = 600 * UNIT;
640     float radius = _tacan_distance_node->getFloatValue() * _scale;
641     float angle = _tacan_bearing_node->getFloatValue() * SG_DEGREES_TO_RADIANS
642             + _angle_offset;
643
644     const osg::Vec2f texBase(1 * UNIT, 3 * UNIT);
645     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
646             * wxRotate(-angle)
647             * osg::Matrixf::translate(0.0f, radius, 0.0f)
648             * wxRotate(angle) * _centerTrans);
649     addQuad(_vertices, _texCoords, m, texBase);
650
651     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:     drawing TACAN"
652     //        << " dist=" << radius
653     //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
654     //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
655     //        << " x=" << x << " y="<< y
656     //        << " size=" << size);
657 }
658
659
660 void
661 wxRadarBg::update_heading_marker()
662 {
663 /*
664     float angle = _view_heading + _angle_offset;
665
666     float x = sin(angle);
667     float y = cos(angle);
668     float s_rot_x = sin(angle + SGD_PI_4);
669     float s_rot_y = cos(angle + SGD_PI_4);
670
671     float size = UNIT * 500;
672 */
673
674     const osg::Vec2f texBase(2 * UNIT, 3 * UNIT);
675     float size = 600 * UNIT;
676     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
677             * wxRotate(_view_heading + _angle_offset));
678
679     if (_display_mode == MAP) {
680         //cout << "Map Mode " << range << endl;
681 //        m *= osg::Matrixf::translate(_scale, _scale, 0.0f);
682     }
683
684     m *= _centerTrans;
685     addQuad(_vertices, _texCoords, m, texBase);
686
687     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:   drawing heading marker"
688     //        << " x,y " << x <<","<< y
689     //        << " dist" << dist
690     //        << " view_heading" << _view_heading * SG_RADIANS_TO_DEGREES
691     //        << " heading " << iradarEcho->heading * SG_RADIANS_TO_DEGREES
692     //        << " angle " << angle * SG_RADIANS_TO_DEGREES);
693 }
694
695
696 void
697 wxRadarBg::center_map()
698 {
699     _lat = _user_lat_node->getDoubleValue();
700     _lon = _user_lon_node->getDoubleValue();
701     _x_offset = _y_offset = 0;
702 }
703
704
705 void
706 wxRadarBg::apply_map_offset()
707 {
708     if (_display_mode != MAP)
709         return;
710     double lat = _user_lat_node->getDoubleValue();
711     double lon = _user_lon_node->getDoubleValue();
712     double bearing, distance, az2;
713     geo_inverse_wgs_84(_lat, _lon, lat, lon, &bearing, &az2, &distance);
714     distance *= SG_METER_TO_NM * _scale;
715     bearing *= SG_DEGREES_TO_RADIANS;
716     _x_offset += sin(bearing) * distance;
717     _y_offset += cos(bearing) * distance;
718     _lat = lat;
719     _lon = lon;
720 }
721
722
723 bool
724 wxRadarBg::withinRadarHorizon(double user_alt, double alt, double range_nm)
725 {
726     // Radar Horizon  = 1.23(ht^1/2 + hr^1/2),
727     //don't allow negative altitudes (an approximation - yes altitudes can be negative)
728
729     if (user_alt < 0)
730         user_alt = 0;
731
732     if (alt < 0)
733         alt = 0;
734
735     double radarhorizon = 1.23 * (sqrt(alt) + sqrt(user_alt));
736     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: horizon " << radarhorizon);
737     return radarhorizon >= range_nm;
738 }
739
740
741 bool
742 wxRadarBg::inRadarRange(int type, double range_nm)
743 {
744     //The Radar Equation:
745     //
746     // MaxRange^4 = (TxPower * AntGain^2 * lambda^2 * sigma)/((constant) * MDS)
747     //
748     // Where (constant) = (4*pi)3 and MDS is the Minimum Detectable Signal power.
749     //
750     // For a given radar we can assume that the only variable is sigma,
751     // the target radar cross section.
752     //
753     // Here, we will use a normalised rcs (sigma) for a standard taget and assume that this
754     // will provide a maximum range of 35nm;
755     //
756     // TODO - make the maximum range adjustable at runtime
757
758     const double sigma[] = {0, 1, 100, 100, 0.001, 0.1, 100, 100, 1, 1};
759     double constant = _radar_ref_rng;
760
761     if (constant <= 0)
762         constant = 35;
763
764     double maxrange = constant * pow(sigma[type], 0.25);
765     SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: max range " << maxrange);
766     return maxrange >= range_nm;
767 }
768
769
770 void
771 wxRadarBg::calcRangeBearing(double lat, double lon, double lat2, double lon2,
772         double &range, double &bearing ) const
773 {
774     // calculate the bearing and range of the second pos from the first
775     double az2, distance;
776     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
777     range = distance *= SG_METER_TO_NM;
778 }
779
780
781 float
782 wxRadarBg::calcRelBearing(float bearing, float heading)
783 {
784     float angle = bearing - heading;
785
786     if (angle >= SG_PI)
787         angle -= 2.0 * SG_PI;
788
789     if (angle < -SG_PI)
790         angle += 2.0 * SG_PI;
791
792     return angle;
793 }
794