1 // navigation display texture
3 // Written by James Turner, forked from wxradar code
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 #include "NavDisplay.hxx"
29 #include <boost/foreach.hpp>
33 #include <osg/Geometry>
34 #include <osg/Matrixf>
35 #include <osg/PrimitiveSet>
36 #include <osg/StateSet>
37 #include <osg/LineWidth>
38 #include <osg/Version>
40 #include <simgear/constants.h>
41 #include <simgear/misc/sg_path.hxx>
42 #include <simgear/scene/model/model.hxx>
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/math/sg_geodesy.hxx>
49 #include <iostream> // for cout, endl
51 using std::stringstream;
53 using std::setprecision;
60 #include <Main/fg_props.hxx>
61 #include <Main/globals.hxx>
62 #include <Cockpit/panel.hxx>
63 #include <Navaids/routePath.hxx>
64 #include <Autopilot/route_mgr.hxx>
65 #include <Navaids/navrecord.hxx>
66 #include <Navaids/navlist.hxx>
67 #include <Navaids/fix.hxx>
68 #include <Airports/simple.hxx>
69 #include <Airports/runways.hxx>
71 #include "instrument_mgr.hxx"
72 #include "od_gauge.hxx"
74 static const char *DEFAULT_FONT = "typewriter.txf";
77 osg::Matrixf degRotation(float angle)
79 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
82 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
85 result.r() = colorNode->getDoubleValue("red", c.r());
86 result.g() = colorNode->getDoubleValue("green", c.g());
87 result.b() = colorNode->getDoubleValue("blue", c.b());
88 result.a() = colorNode->getDoubleValue("alpha", c.a());
92 static osgText::Text::AlignmentType readAlignment(const std::string& t)
94 if (t == "left-top") {
95 return osgText::Text::LEFT_TOP;
96 } else if (t == "left-center") {
97 return osgText::Text::LEFT_CENTER;
98 } else if (t == "left-bottom") {
99 return osgText::Text::LEFT_BOTTOM;
100 } else if (t == "center-top") {
101 return osgText::Text::CENTER_TOP;
102 } else if (t == "center-center") {
103 return osgText::Text::CENTER_CENTER;
104 } else if (t == "center-bottom") {
105 return osgText::Text::CENTER_BOTTOM;
106 } else if (t == "right-top") {
107 return osgText::Text::RIGHT_TOP;
108 } else if (t == "right-center") {
109 return osgText::Text::RIGHT_CENTER;
110 } else if (t == "right-bottom") {
111 return osgText::Text::RIGHT_BOTTOM;
112 } else if (t == "left-baseline") {
113 return osgText::Text::LEFT_BASE_LINE;
114 } else if (t == "center-baseline") {
115 return osgText::Text::CENTER_BASE_LINE;
116 } else if (t == "right-baseline") {
117 return osgText::Text::RIGHT_BASE_LINE;
120 return osgText::Text::BASE_LINE;
123 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
126 static char buf[512];
127 if (format.find('d') >= 0) {
128 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
132 if (format.find('s') >= 0) {
133 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
137 // assume it's a double/float
138 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
142 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
144 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
145 return osg::Vec2(r.x(), r.y());
148 ///////////////////////////////////////////////////////////////////
153 void initFromNode(SGPropertyNode* node)
155 type = node->getStringValue("type");
156 enable = sgReadCondition(fgGetNode("/"), node->getChild("enable"));
158 while (node->hasChild("state", n)) {
159 string m = node->getChild("state", n++)->getStringValue();
161 excluded_states.insert(m.substr(1));
163 required_states.insert(m);
165 } // of matches parsing
167 xy0.x() = node->getFloatValue("x0", -5);
168 xy0.y() = node->getFloatValue("y0", -5);
169 xy1.x() = node->getFloatValue("x1", 5);
170 xy1.y() = node->getFloatValue("y1", 5);
172 double texSize = node->getFloatValue("texture-size", 1.0);
174 uv0.x() = node->getFloatValue("u0", 0) / texSize;
175 uv0.y() = node->getFloatValue("v0", 0) / texSize;
176 uv1.x() = node->getFloatValue("u1", 1) / texSize;
177 uv1.y() = node->getFloatValue("v1", 1) / texSize;
179 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
180 priority = node->getIntValue("priority", 0);
181 zOrder = node->getIntValue("zOrder", 0);
182 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
183 roundPos = node->getBoolValue("round-position", true);
185 if (node->hasChild("text")) {
187 alignment = readAlignment(node->getStringValue("text-align"));
188 textTemplate = node->getStringValue("text");
189 textOffset.x() = node->getFloatValue("text-offset-x", 0);
190 textOffset.y() = node->getFloatValue("text-offset-y", 0);
191 textColor = readColor(node->getChild("text-color"), color);
194 drawLine = node->getBoolValue("draw-line", false);
195 lineColor = readColor(node->getChild("line-color"), color);
196 drawRouteLeg = node->getBoolValue("draw-line", false);
198 stretchSymbol = node->getBoolValue("stretch-symbol", false);
200 stretchY2 = node->getFloatValue("y2");
201 stretchY3 = node->getFloatValue("y3");
202 stretchV2 = node->getFloatValue("v2");
203 stretchV3 = node->getFloatValue("v3");
208 bool enabled; // cached enabled state
211 string_set required_states;
212 string_set excluded_states;
220 bool rotateToHeading;
221 bool roundPos; ///< should position be rounded to integer values
224 osg::Vec2 textOffset;
225 osgText::Text::AlignmentType alignment;
231 // symbol stretching creates three quads (instead of one) - a start,
232 // middle and end quad, positioned along the line of the symbol.
233 // X (and U) axis values determined by the values above, so we only need
234 // to define the Y (and V) values to build the other quads.
236 double stretchY2, stretchY3;
237 double stretchV2, stretchV3;
241 bool matches(const string_set& states) const
243 string_set::const_iterator it = states.begin(),
245 for (; it != end; ++it) {
246 if (required_states.count(*it) == 0) {
247 // required state not matched
251 if (excluded_states.count(*it) > 0) {
252 // excluded state matched
255 } // of applicable states iteration
257 return true; // matches!
264 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
271 osg::Vec2 pos; // projected position
274 SymbolDef* definition;
275 SGPropertyNode_ptr props;
279 assert(definition->hasText);
285 for (; pos < (int) definition->textTemplate.size();) {
286 pos = definition->textTemplate.find('{', pos);
287 if (pos == -1) { // no more replacements
288 r.append(definition->textTemplate.substr(lastPos));
292 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
294 int endReplacement = definition->textTemplate.find('}', pos+1);
295 if (endReplacement <= pos) {
296 return "bad replacement";
299 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
300 // look for formatter in spec
301 int colonPos = spec.find(':');
303 // simple replacement
304 r.append(props->getStringValue(spec));
306 string format = spec.substr(colonPos + 1);
307 string prop = spec.substr(0, colonPos);
308 r.append(formatPropertyValue(props->getNode(prop), format));
311 lastPos = endReplacement + 1;
318 //////////////////////////////////////////////////////////////////
320 NavDisplay::NavDisplay(SGPropertyNode *node) :
321 _name(node->getStringValue("name", "nd")),
322 _num(node->getIntValue("number", 0)),
324 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
333 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
334 _font_node = _Instrument->getNode("font", true);
336 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
337 INITFONT("name", DEFAULT_FONT, String);
338 INITFONT("size", 8, Float);
339 INITFONT("line-spacing", 0.25, Float);
340 INITFONT("color/red", 0, Float);
341 INITFONT("color/green", 0.8, Float);
342 INITFONT("color/blue", 0, Float);
343 INITFONT("color/alpha", 1, Float);
349 NavDisplay::~NavDisplay()
357 _serviceable_node = _Instrument->getNode("serviceable", true);
359 // texture name to use in 2D and 3D instruments
360 _texture_path = _Instrument->getStringValue("radar-texture-path",
361 "Aircraft/Instruments/Textures/od_wxradar.rgb");
362 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
364 string path = _Instrument->getStringValue("symbol-texture-path",
365 "Aircraft/Instruments/Textures/nd-symbols.png");
366 SGPath tpath = globals->resolve_aircraft_path(path);
368 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
369 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
371 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
372 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
373 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
376 _user_lat_node = fgGetNode("/position/latitude-deg", true);
377 _user_lon_node = fgGetNode("/position/longitude-deg", true);
378 _user_alt_node = fgGetNode("/position/altitude-ft", true);
380 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
382 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
383 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
385 // OSG geometry setup
386 _radarGeode = new osg::Geode;
388 _geom = new osg::Geometry;
389 _geom->setUseDisplayList(false);
391 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
392 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
394 // Initially allocate space for 128 quads
395 _vertices = new osg::Vec2Array;
396 _vertices->setDataVariance(osg::Object::DYNAMIC);
397 _vertices->reserve(128 * 4);
398 _geom->setVertexArray(_vertices);
399 _texCoords = new osg::Vec2Array;
400 _texCoords->setDataVariance(osg::Object::DYNAMIC);
401 _texCoords->reserve(128 * 4);
402 _geom->setTexCoordArray(0, _texCoords);
404 _quadColors = new osg::Vec4Array;
405 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
406 _geom->setColorArray(_quadColors);
408 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
409 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
410 _geom->addPrimitiveSet(_symbolPrimSet);
412 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
413 osg::Vec3f(256.0f, 256.0f, 0.0f)));
414 _radarGeode->addDrawable(_geom);
416 // Texture in the 2D panel system
417 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
419 _lineGeometry = new osg::Geometry;
420 _lineGeometry->setUseDisplayList(false);
421 stateSet = _lineGeometry->getOrCreateStateSet();
422 osg::LineWidth *lw = new osg::LineWidth();
424 stateSet->setAttribute(lw);
426 _lineVertices = new osg::Vec2Array;
427 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
428 _lineVertices->reserve(128 * 4);
429 _lineGeometry->setVertexArray(_lineVertices);
432 _lineColors = new osg::Vec4Array;
433 _lineColors->setDataVariance(osg::Object::DYNAMIC);
434 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
435 _lineGeometry->setColorArray(_lineColors);
437 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
438 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
439 _lineGeometry->addPrimitiveSet(_linePrimSet);
441 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
442 osg::Vec3f(256.0f, 256.0f, 0.0f)));
444 _radarGeode->addDrawable(_lineGeometry);
446 _textGeode = new osg::Geode;
448 osg::Camera *camera = _odg->getCamera();
449 camera->addChild(_radarGeode.get());
450 camera->addChild(_textGeode.get());
451 osg::Texture2D* tex = _odg->getTexture();
452 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
453 0, tex->getTextureHeight());
459 NavDisplay::update (double delta_time_sec)
461 if (!fgGetBool("sim/sceneryloaded", false)) {
465 if (!_odg || !_serviceable_node->getBoolValue()) {
466 _Instrument->setStringValue("status", "");
470 _time += delta_time_sec;
471 if (_time < _updateInterval){
474 _time -= _updateInterval;
476 _rangeNm = _Instrument->getFloatValue("range", 40.0);
477 if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
478 _view_heading = fgGetDouble("/orientation/heading-deg");
480 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
483 _scale = _odg->size() / _rangeNm;
485 double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
486 double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
487 _centerTrans = osg::Matrixf::translate(xCenterFrac * _odg->size(),
488 yCenterFrac * _odg->size(), 0.0);
490 // scale from nm to display units, rotate so aircraft heading is up
491 // (as opposed to north), and compensate for centering
492 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
493 degRotation(-_view_heading) * _centerTrans;
495 _pos = SGGeod::fromDegFt(_user_lon_node->getDoubleValue(),
496 _user_lat_node->getDoubleValue(),
497 _user_alt_node->getDoubleValue());
500 _lineVertices->clear();
501 _lineColors->clear();
503 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
505 BOOST_FOREACH(SymbolDef* def, _rules) {
506 def->enabled = def->enable->test();
513 limitDisplayedSymbols();
516 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
517 _symbolPrimSet->dirty();
518 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
519 _linePrimSet->dirty();
524 NavDisplay::updateFont()
526 float red = _font_node->getFloatValue("color/red");
527 float green = _font_node->getFloatValue("color/green");
528 float blue = _font_node->getFloatValue("color/blue");
529 float alpha = _font_node->getFloatValue("color/alpha");
530 _font_color.set(red, green, blue, alpha);
532 _font_size = _font_node->getFloatValue("size");
533 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
534 string path = _font_node->getStringValue("name", DEFAULT_FONT);
537 if (path[0] != '/') {
538 tpath = globals->get_fg_root();
539 tpath.append("Fonts");
545 #if (FG_OSG_VERSION >= 21000)
546 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
547 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
549 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str());
554 _font->setMinFilterHint(osg::Texture::NEAREST);
555 _font->setMagFilterHint(osg::Texture::NEAREST);
556 _font->setGlyphImageMargin(0);
557 _font->setGlyphImageMarginRatio(0);
561 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
563 SymbolDef* def = sym->definition;
567 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
569 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
571 if (def->rotateToHeading) {
572 osg::Matrixf m(degRotation(sym->headingDeg));
573 for (int i=0; i<4; ++i) {
574 verts[i] = mult(verts[i], m);
578 osg::Vec2 pos = sym->pos;
580 pos = osg::Vec2((int) pos.x(), (int) pos.y());
583 _texCoords->push_back(def->uv0);
584 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
585 _texCoords->push_back(def->uv1);
586 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
588 for (int i=0; i<4; ++i) {
589 _vertices->push_back(verts[i] + pos);
590 _quadColors->push_back(def->color);
593 if (def->stretchSymbol) {
594 osg::Vec2 stretchVerts[4];
595 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
596 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
597 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
598 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
600 osg::Matrixf m(degRotation(sym->headingDeg));
601 for (int i=0; i<4; ++i) {
602 stretchVerts[i] = mult(stretchVerts[i], m);
606 _vertices->push_back(verts[2] + pos);
607 _vertices->push_back(stretchVerts[1] + sym->endPos);
608 _vertices->push_back(stretchVerts[0] + sym->endPos);
609 _vertices->push_back(verts[3] + pos);
611 _texCoords->push_back(def->uv1);
612 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
613 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
614 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
616 for (int i=0; i<4; ++i) {
617 _quadColors->push_back(def->color);
620 // quad three, for the end portion
621 for (int i=0; i<4; ++i) {
622 _vertices->push_back(stretchVerts[i] + sym->endPos);
623 _quadColors->push_back(def->color);
626 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
627 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
628 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
629 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
633 addLine(sym->pos, sym->endPos, def->lineColor);
640 osgText::Text* t = new osgText::Text;
641 t->setFont(_font.get());
642 t->setFontResolution(12, 12);
643 t->setCharacterSize(_font_size);
644 t->setLineSpacing(_font_spacing);
645 t->setColor(def->textColor);
646 t->setAlignment(def->alignment);
647 t->setText(sym->text());
650 osg::Vec2 textPos = def->textOffset + pos;
651 // ensure we use ints here, or text visual quality goes bad
652 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
653 _textGeode->addDrawable(t);
656 class OrderByPriority
659 bool operator()(SymbolInstance* a, SymbolInstance* b)
661 return a->definition->priority > b->definition->priority;
665 void NavDisplay::limitDisplayedSymbols()
667 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols");
668 if (_symbols.size() <= maxSymbols) {
669 _excessDataNode->setBoolValue(false);
673 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
674 _symbols.resize(maxSymbols);
675 _excessDataNode->setBoolValue(true);
681 bool operator()(SymbolInstance* a, SymbolInstance* b)
683 return a->definition->zOrder > b->definition->zOrder;
687 void NavDisplay::addSymbolsToScene()
689 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
690 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
691 addSymbolToScene(sym);
695 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
697 _lineVertices->push_back(a);
698 _lineVertices->push_back(b);
699 _lineColors->push_back(color);
700 _lineColors->push_back(color);
703 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
705 osg::Vec3 p(0, rangeNm, 0.0);
706 p = degRotation(bearingDeg).preMult(p);
707 p = _projectMat.preMult(p);
708 return osg::Vec2(p.x(), p.y());
711 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
713 double rangeM, bearing, az2;
714 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
715 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
718 class Filter : public FGPositioned::Filter
721 virtual bool pass(FGPositioned* aPos) const
723 if (aPos->type() == FGPositioned::FIX) {
724 string ident(aPos->ident());
725 // ignore fixes which end in digits
726 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
734 virtual FGPositioned::Type minType() const {
735 return FGPositioned::AIRPORT;
738 virtual FGPositioned::Type maxType() const {
739 return FGPositioned::OBSTACLE;
743 void NavDisplay::findItems()
746 FGPositioned::List items =
747 FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
749 FGPositioned::List::const_iterator it;
750 for (it = items.begin(); it != items.end(); ++it) {
751 foundPositionedItem(*it);
755 void NavDisplay::processRoute()
757 _routeSources.clear();
758 RoutePath path(_route->waypts());
759 int current = _route->currentIndex();
761 for (int w=0; w<_route->numWaypts(); ++w) {
762 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
763 _routeSources.insert(wpt->source());
766 state.insert("on-active-route");
769 state.insert("passed");
773 state.insert("current-wp");
777 state.insert("future");
780 if (w == (current + 1)) {
781 state.insert("next-wp");
784 SymbolDefVector rules;
785 findRules(wpt->type() , state, rules);
787 return; // no rules matched, we can skip this item
790 SGGeod g = path.positionForIndex(w);
791 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
793 computeWayptPropsAndHeading(wpt, g, vars, heading);
795 osg::Vec2 projected = projectGeod(g);
796 BOOST_FOREACH(SymbolDef* r, rules) {
797 addSymbolInstance(projected, heading, r, vars);
799 if (r->drawRouteLeg) {
800 SGGeodVec gv(path.pathForIndex(w));
802 osg::Vec2 pr = projectGeod(gv[0]);
803 for (unsigned int i=1; i<gv.size(); ++i) {
804 osg::Vec2 p = projectGeod(gv[i]);
805 addLine(pr, p, r->lineColor);
809 } // of leg drawing enabled
810 } // of matching rules iteration
811 } // of waypoints iteration
814 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
817 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
818 nd->setIntValue("radial", heading);
819 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
821 heading = nd->getDoubleValue("leg-bearing-true-deg");
824 void NavDisplay::processNavRadios()
826 _nav1Station = processNavRadio(_navRadio1Node);
827 _nav2Station = processNavRadio(_navRadio2Node);
829 foundPositionedItem(_nav1Station);
830 foundPositionedItem(_nav2Station);
833 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
835 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
836 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
837 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
838 // station was not found
846 bool NavDisplay::anyRuleForType(const string& type) const
848 BOOST_FOREACH(SymbolDef* r, _rules) {
853 if (r->type == type) {
861 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
863 BOOST_FOREACH(SymbolDef* r, _rules) {
864 if (!r->enabled || (r->type != type)) {
868 if (r->matches(states)) {
871 } // of rules iteration
876 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
878 BOOST_FOREACH(SymbolDef* candidate, _rules) {
879 if (!candidate->enabled) {
883 if (candidate->matches(states)) {
884 rules.push_back(candidate);
889 void NavDisplay::foundPositionedItem(FGPositioned* pos)
895 string type = FGPositioned::nameForType(pos->type());
896 if (!anyRuleForType(type)) {
897 return; // not diplayed at all, we're done
901 computePositionedState(pos, states);
903 SymbolDefVector rules;
904 findRules(type, states, rules);
906 return; // no rules matched, we can skip this item
909 SGPropertyNode_ptr vars(new SGPropertyNode);
911 computePositionedPropsAndHeading(pos, vars, heading);
913 osg::Vec2 projected = projectGeod(pos->geod());
914 BOOST_FOREACH(SymbolDef* r, rules) {
915 addSymbolInstance(projected, heading, r, vars);
919 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
921 nd->setStringValue("id", pos->ident());
922 nd->setStringValue("name", pos->name());
923 nd->setDoubleValue("elevation-ft", pos->elevation());
924 nd->setIntValue("heading-deg", 0);
926 switch (pos->type()) {
927 case FGPositioned::VOR:
928 case FGPositioned::LOC: {
929 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
930 nd->setDoubleValue("frequency-mhz", nav->get_freq());
932 if (pos == _nav1Station) {
933 nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
934 } else if (pos == _nav2Station) {
935 nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
941 case FGPositioned::AIRPORT:
942 case FGPositioned::SEAPORT:
943 case FGPositioned::HELIPORT:
947 case FGPositioned::RUNWAY: {
948 FGRunway* rwy = static_cast<FGRunway*>(pos);
949 nd->setDoubleValue("heading-deg", rwy->headingDeg());
950 nd->setIntValue("length-ft", rwy->lengthFt());
951 nd->setStringValue("airport", rwy->airport()->ident());
960 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
962 if (_routeSources.count(pos) != 0) {
963 states.insert("on-active-route");
966 switch (pos->type()) {
967 case FGPositioned::VOR:
968 case FGPositioned::LOC:
969 if (pos == _nav1Station) {
970 states.insert("tuned");
971 states.insert("nav1");
974 if (pos == _nav2Station) {
975 states.insert("tuned");
976 states.insert("nav2");
980 case FGPositioned::AIRPORT:
981 case FGPositioned::SEAPORT:
982 case FGPositioned::HELIPORT:
984 // once the FMS system has some way to tell us about them, of course
986 if (pos == _route->departureAirport()) {
987 states.insert("departure");
990 if (pos == _route->destinationAirport()) {
991 states.insert("destination");
995 case FGPositioned::RUNWAY:
996 if (pos == _route->departureRunway()) {
997 states.insert("departure");
1000 if (pos == _route->destinationRunway()) {
1001 states.insert("destination");
1005 case FGPositioned::OBSTACLE:
1007 FGObstacle* obs = (FGObstacle*) pos;
1009 states.insert("lit");
1012 if (obj->getHeightAGLFt() >= 1000) {
1013 states.insert("greater-1000-ft");
1020 } // FGPositioned::Type switch
1023 void NavDisplay::processAI()
1025 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1026 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1027 SGPropertyNode *model = ai->getChild(i);
1028 if (!model->nChildren()) {
1032 // prefix types with 'ai-', to avoid any chance of namespace collisions
1033 // with fg-positioned.
1035 computeAIStates(model, ss);
1036 SymbolDefVector rules;
1037 findRules(string("ai-") + model->getName(), ss, rules);
1038 if (rules.empty()) {
1039 return; // no rules matched, we can skip this item
1042 double heading = model->getDoubleValue("orientation/true-heading-deg");
1043 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1044 model->getDoubleValue("position/latitude-deg"),
1045 model->getDoubleValue("position/altitude-ft"));
1046 // compute some additional props
1047 int fl = (aiModelPos.getElevationFt() / 1000);
1048 model->setIntValue("flight-level", fl * 10);
1050 osg::Vec2 projected = projectGeod(aiModelPos);
1051 BOOST_FOREACH(SymbolDef* r, rules) {
1052 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1054 } // of ai models iteration
1057 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1059 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1060 if (threatLevel >= 0) {
1061 states.insert("tcas");
1062 // states.insert("tcas-threat-level-" + itoa(threatLevel));
1065 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1066 if (vspeed < -3.0) {
1067 states.insert("descending");
1068 } else if (vspeed > 3.0) {
1069 states.insert("climbing");
1073 void NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1075 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1076 _symbols.push_back(sym);