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