Debian Codegraph @

src/Cockpit/wxradar.cxx

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