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