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') != string::npos) {
128 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
132 if (format.find('s') != string::npos) {
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 ///////////////////////////////////////////////////////////////////
157 bool initFromNode(SGPropertyNode* node)
159 type = node->getStringValue("type");
160 SGPropertyNode* enableNode = node->getChild("enable");
162 enable = sgReadCondition(fgGetNode("/"), enableNode);
166 while (node->hasChild("state", n)) {
167 string m = node->getChild("state", n++)->getStringValue();
169 excluded_states.insert(m.substr(1));
171 required_states.insert(m);
173 } // of matches parsing
175 if (node->hasChild("width")) {
176 float w = node->getFloatValue("width");
177 float h = node->getFloatValue("height", w);
183 xy0.x() = node->getFloatValue("x0", 0.0);
184 xy0.y() = node->getFloatValue("y0", 0.0);
185 xy1.x() = node->getFloatValue("x1", 5);
186 xy1.y() = node->getFloatValue("y1", 5);
189 double texSize = node->getFloatValue("texture-size", 1.0);
191 uv0.x() = node->getFloatValue("u0", 0) / texSize;
192 uv0.y() = node->getFloatValue("v0", 0) / texSize;
193 uv1.x() = node->getFloatValue("u1", 1) / texSize;
194 uv1.y() = node->getFloatValue("v1", 1) / texSize;
196 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
197 priority = node->getIntValue("priority", 0);
198 zOrder = node->getIntValue("zOrder", 0);
199 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
200 roundPos = node->getBoolValue("round-position", true);
202 if (node->hasChild("text")) {
204 alignment = readAlignment(node->getStringValue("text-align"));
205 textTemplate = node->getStringValue("text");
206 textOffset.x() = node->getFloatValue("text-offset-x", 0);
207 textOffset.y() = node->getFloatValue("text-offset-y", 0);
208 textColor = readColor(node->getChild("text-color"), color);
211 drawLine = node->getBoolValue("draw-line", false);
212 lineColor = readColor(node->getChild("line-color"), color);
213 drawRouteLeg = node->getBoolValue("draw-leg", false);
215 stretchSymbol = node->getBoolValue("stretch-symbol", false);
217 stretchY2 = node->getFloatValue("y2");
218 stretchY3 = node->getFloatValue("y3");
219 stretchV2 = node->getFloatValue("v2");
220 stretchV3 = node->getFloatValue("v3");
227 bool enabled; // cached enabled state
230 string_set required_states;
231 string_set excluded_states;
239 bool rotateToHeading;
240 bool roundPos; ///< should position be rounded to integer values
243 osg::Vec2 textOffset;
244 osgText::Text::AlignmentType alignment;
250 // symbol stretching creates three quads (instead of one) - a start,
251 // middle and end quad, positioned along the line of the symbol.
252 // X (and U) axis values determined by the values above, so we only need
253 // to define the Y (and V) values to build the other quads.
255 double stretchY2, stretchY3;
256 double stretchV2, stretchV3;
260 bool matches(const string_set& states) const
262 BOOST_FOREACH(const string& s, required_states) {
263 if (states.count(s) == 0) {
268 BOOST_FOREACH(const string& s, excluded_states) {
269 if (states.count(s) != 0) {
281 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
288 osg::Vec2 pos; // projected position
291 SymbolDef* definition;
292 SGPropertyNode_ptr props;
296 assert(definition->hasText);
301 size_t pos = definition->textTemplate.find('{', lastPos);
302 if (pos == string::npos) { // no more replacements
303 r.append(definition->textTemplate.substr(lastPos));
307 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
309 size_t endReplacement = definition->textTemplate.find('}', pos+1);
310 if (endReplacement <= pos) {
311 return "bad replacement";
314 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
315 // look for formatter in spec
316 size_t colonPos = spec.find(':');
317 if (colonPos == string::npos) {
318 // simple replacement
319 r.append(props->getStringValue(spec));
321 string format = spec.substr(colonPos + 1);
322 string prop = spec.substr(0, colonPos);
323 r.append(formatPropertyValue(props->getNode(prop), format));
326 lastPos = endReplacement + 1;
333 //////////////////////////////////////////////////////////////////
335 NavDisplay::NavDisplay(SGPropertyNode *node) :
336 _name(node->getStringValue("name", "nd")),
337 _num(node->getIntValue("number", 0)),
339 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
348 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
349 _font_node = _Instrument->getNode("font", true);
351 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
352 INITFONT("name", DEFAULT_FONT, String);
353 INITFONT("size", 8, Float);
354 INITFONT("line-spacing", 0.25, Float);
355 INITFONT("color/red", 0, Float);
356 INITFONT("color/green", 0.8, Float);
357 INITFONT("color/blue", 0, Float);
358 INITFONT("color/alpha", 1, Float);
361 SGPropertyNode* symbolsNode = node->getNode("symbols");
362 SGPropertyNode* symbol;
364 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
365 SymbolDef* def = new SymbolDef;
366 if (!def->initFromNode(symbol)) {
371 _rules.push_back(def);
372 } // of symbol definition parsing
376 NavDisplay::~NavDisplay()
384 _serviceable_node = _Instrument->getNode("serviceable", true);
386 // texture name to use in 2D and 3D instruments
387 _texture_path = _Instrument->getStringValue("radar-texture-path",
388 "Aircraft/Instruments/Textures/od_wxradar.rgb");
389 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
391 string path = _Instrument->getStringValue("symbol-texture-path",
392 "Aircraft/Instruments/Textures/nd-symbols.png");
393 SGPath tpath = globals->resolve_aircraft_path(path);
394 if (!tpath.exists()) {
395 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
398 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
399 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
401 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
402 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
403 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
406 _user_lat_node = fgGetNode("/position/latitude-deg", true);
407 _user_lon_node = fgGetNode("/position/longitude-deg", true);
408 _user_alt_node = fgGetNode("/position/altitude-ft", true);
410 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
412 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
413 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
415 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
416 _excessDataNode->setBoolValue(false);
418 // OSG geometry setup
419 _radarGeode = new osg::Geode;
421 _geom = new osg::Geometry;
422 _geom->setUseDisplayList(false);
424 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
425 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
427 // Initially allocate space for 128 quads
428 _vertices = new osg::Vec2Array;
429 _vertices->setDataVariance(osg::Object::DYNAMIC);
430 _vertices->reserve(128 * 4);
431 _geom->setVertexArray(_vertices);
432 _texCoords = new osg::Vec2Array;
433 _texCoords->setDataVariance(osg::Object::DYNAMIC);
434 _texCoords->reserve(128 * 4);
435 _geom->setTexCoordArray(0, _texCoords);
437 _quadColors = new osg::Vec4Array;
438 _quadColors->setDataVariance(osg::Object::DYNAMIC);
439 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
440 _geom->setColorArray(_quadColors);
442 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
443 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
444 _geom->addPrimitiveSet(_symbolPrimSet);
446 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
447 osg::Vec3f(256.0f, 256.0f, 0.0f)));
449 _radarGeode->addDrawable(_geom);
451 // Texture in the 2D panel system
452 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
454 _lineGeometry = new osg::Geometry;
455 _lineGeometry->setUseDisplayList(false);
456 stateSet = _lineGeometry->getOrCreateStateSet();
457 osg::LineWidth *lw = new osg::LineWidth();
459 stateSet->setAttribute(lw);
461 _lineVertices = new osg::Vec2Array;
462 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
463 _lineVertices->reserve(128 * 4);
464 _lineGeometry->setVertexArray(_lineVertices);
467 _lineColors = new osg::Vec4Array;
468 _lineColors->setDataVariance(osg::Object::DYNAMIC);
469 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
470 _lineGeometry->setColorArray(_lineColors);
472 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
473 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
474 _lineGeometry->addPrimitiveSet(_linePrimSet);
476 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
477 osg::Vec3f(256.0f, 256.0f, 0.0f)));
479 _radarGeode->addDrawable(_lineGeometry);
481 _textGeode = new osg::Geode;
483 osg::Camera *camera = _odg->getCamera();
484 camera->addChild(_radarGeode.get());
485 camera->addChild(_textGeode.get());
486 osg::Texture2D* tex = _odg->getTexture();
487 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
488 0, tex->getTextureHeight());
494 NavDisplay::update (double delta_time_sec)
496 if (!fgGetBool("sim/sceneryloaded", false)) {
500 if (!_odg || !_serviceable_node->getBoolValue()) {
501 _Instrument->setStringValue("status", "");
505 _time += delta_time_sec;
506 if (_time < _updateInterval){
509 _time -= _updateInterval;
511 _rangeNm = _Instrument->getFloatValue("range", 40.0);
512 if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
513 _view_heading = fgGetDouble("/orientation/heading-deg");
515 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
518 _scale = _odg->size() / _rangeNm;
520 double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
521 double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
522 _centerTrans = osg::Matrixf::translate(xCenterFrac * _odg->size(),
523 yCenterFrac * _odg->size(), 0.0);
525 // scale from nm to display units, rotate so aircraft heading is up
526 // (as opposed to north), and compensate for centering
527 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
528 degRotation(-_view_heading) * _centerTrans;
530 _pos = SGGeod::fromDegFt(_user_lon_node->getDoubleValue(),
531 _user_lat_node->getDoubleValue(),
532 _user_alt_node->getDoubleValue());
535 _lineVertices->clear();
536 _lineColors->clear();
537 _quadColors->clear();
539 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
541 BOOST_FOREACH(SymbolDef* def, _rules) {
543 def->enabled = def->enable->test();
553 limitDisplayedSymbols();
556 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
557 _symbolPrimSet->dirty();
558 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
559 _linePrimSet->dirty();
564 NavDisplay::updateFont()
566 float red = _font_node->getFloatValue("color/red");
567 float green = _font_node->getFloatValue("color/green");
568 float blue = _font_node->getFloatValue("color/blue");
569 float alpha = _font_node->getFloatValue("color/alpha");
570 _font_color.set(red, green, blue, alpha);
572 _font_size = _font_node->getFloatValue("size");
573 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
574 string path = _font_node->getStringValue("name", DEFAULT_FONT);
577 if (path[0] != '/') {
578 tpath = globals->get_fg_root();
579 tpath.append("Fonts");
585 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
586 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
590 _font->setMinFilterHint(osg::Texture::NEAREST);
591 _font->setMagFilterHint(osg::Texture::NEAREST);
592 _font->setGlyphImageMargin(0);
593 _font->setGlyphImageMarginRatio(0);
597 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
599 SymbolDef* def = sym->definition;
603 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
605 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
607 if (def->rotateToHeading) {
608 osg::Matrixf m(degRotation(sym->headingDeg));
609 for (int i=0; i<4; ++i) {
610 verts[i] = mult(verts[i], m);
614 osg::Vec2 pos = sym->pos;
616 pos = osg::Vec2((int) pos.x(), (int) pos.y());
619 _texCoords->push_back(def->uv0);
620 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
621 _texCoords->push_back(def->uv1);
622 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
624 for (int i=0; i<4; ++i) {
625 _vertices->push_back(verts[i] + pos);
626 _quadColors->push_back(def->color);
629 if (def->stretchSymbol) {
630 osg::Vec2 stretchVerts[4];
631 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
632 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
633 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
634 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
636 osg::Matrixf m(degRotation(sym->headingDeg));
637 for (int i=0; i<4; ++i) {
638 stretchVerts[i] = mult(stretchVerts[i], m);
642 _vertices->push_back(verts[2] + pos);
643 _vertices->push_back(stretchVerts[1] + sym->endPos);
644 _vertices->push_back(stretchVerts[0] + sym->endPos);
645 _vertices->push_back(verts[3] + pos);
647 _texCoords->push_back(def->uv1);
648 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
649 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
650 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
652 for (int i=0; i<4; ++i) {
653 _quadColors->push_back(def->color);
656 // quad three, for the end portion
657 for (int i=0; i<4; ++i) {
658 _vertices->push_back(stretchVerts[i] + sym->endPos);
659 _quadColors->push_back(def->color);
662 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
663 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
664 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
665 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
669 addLine(sym->pos, sym->endPos, def->lineColor);
676 osgText::Text* t = new osgText::Text;
677 t->setFont(_font.get());
678 t->setFontResolution(12, 12);
679 t->setCharacterSize(_font_size);
680 t->setLineSpacing(_font_spacing);
681 t->setColor(def->textColor);
682 t->setAlignment(def->alignment);
683 t->setText(sym->text());
686 osg::Vec2 textPos = def->textOffset + pos;
687 // ensure we use ints here, or text visual quality goes bad
688 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
689 _textGeode->addDrawable(t);
692 class OrderByPriority
695 bool operator()(SymbolInstance* a, SymbolInstance* b)
697 return a->definition->priority > b->definition->priority;
701 void NavDisplay::limitDisplayedSymbols()
703 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
704 if (_symbols.size() <= maxSymbols) {
705 _excessDataNode->setBoolValue(false);
709 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
710 _symbols.resize(maxSymbols);
711 _excessDataNode->setBoolValue(true);
717 bool operator()(SymbolInstance* a, SymbolInstance* b)
719 return a->definition->zOrder > b->definition->zOrder;
723 void NavDisplay::addSymbolsToScene()
725 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
726 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
727 addSymbolToScene(sym);
731 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
733 _lineVertices->push_back(a);
734 _lineVertices->push_back(b);
735 _lineColors->push_back(color);
736 _lineColors->push_back(color);
739 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
741 osg::Vec3 p(0, rangeNm, 0.0);
742 p = degRotation(bearingDeg).preMult(p);
743 p = _projectMat.preMult(p);
744 return osg::Vec2(p.x(), p.y());
747 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
749 double rangeM, bearing, az2;
750 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
751 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
754 class Filter : public FGPositioned::Filter
757 double minRunwayLengthFt;
759 virtual bool pass(FGPositioned* aPos) const
761 if (aPos->type() == FGPositioned::FIX) {
762 string ident(aPos->ident());
763 // ignore fixes which end in digits
764 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
769 if (aPos->type() == FGPositioned::AIRPORT) {
770 FGAirport* apt = (FGAirport*) aPos;
771 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
779 virtual FGPositioned::Type minType() const {
780 return FGPositioned::AIRPORT;
783 virtual FGPositioned::Type maxType() const {
784 return FGPositioned::OBSTACLE;
788 void NavDisplay::findItems()
791 filt.minRunwayLengthFt = 2000;
793 FGPositioned::List items =
794 FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
796 FGPositioned::List::const_iterator it;
797 for (it = items.begin(); it != items.end(); ++it) {
798 foundPositionedItem(*it);
802 void NavDisplay::processRoute()
804 _routeSources.clear();
805 RoutePath path(_route->waypts());
806 int current = _route->currentIndex();
808 for (int w=0; w<_route->numWaypts(); ++w) {
809 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
810 _routeSources.insert(wpt->source());
813 state.insert("on-active-route");
816 state.insert("passed");
820 state.insert("current-wp");
824 state.insert("future");
827 if (w == (current + 1)) {
828 state.insert("next-wp");
831 SymbolDefVector rules;
832 findRules("waypoint" , state, rules);
834 return; // no rules matched, we can skip this item
837 SGGeod g = path.positionForIndex(w);
838 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
840 computeWayptPropsAndHeading(wpt, g, vars, heading);
842 osg::Vec2 projected = projectGeod(g);
843 BOOST_FOREACH(SymbolDef* r, rules) {
844 addSymbolInstance(projected, heading, r, vars);
846 if (r->drawRouteLeg) {
847 SGGeodVec gv(path.pathForIndex(w));
849 osg::Vec2 pr = projectGeod(gv[0]);
850 for (unsigned int i=1; i<gv.size(); ++i) {
851 osg::Vec2 p = projectGeod(gv[i]);
852 addLine(pr, p, r->lineColor);
856 } // of leg drawing enabled
857 } // of matching rules iteration
858 } // of waypoints iteration
861 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
864 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
865 nd->setIntValue("radial", heading);
866 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
868 heading = nd->getDoubleValue("leg-bearing-true-deg");
871 void NavDisplay::processNavRadios()
873 _nav1Station = processNavRadio(_navRadio1Node);
874 _nav2Station = processNavRadio(_navRadio2Node);
876 foundPositionedItem(_nav1Station);
877 foundPositionedItem(_nav2Station);
880 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
882 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
883 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
884 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
885 // station was not found
893 bool NavDisplay::anyRuleForType(const string& type) const
895 BOOST_FOREACH(SymbolDef* r, _rules) {
900 if (r->type == type) {
908 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
910 BOOST_FOREACH(SymbolDef* r, _rules) {
911 if (!r->enabled || (r->type != type)) {
915 if (r->matches(states)) {
918 } // of rules iteration
923 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
925 BOOST_FOREACH(SymbolDef* candidate, _rules) {
926 if (!candidate->enabled || (candidate->type != type)) {
930 if (candidate->matches(states)) {
931 rules.push_back(candidate);
936 void NavDisplay::foundPositionedItem(FGPositioned* pos)
942 string type = FGPositioned::nameForType(pos->type());
943 if (!anyRuleForType(type)) {
944 return; // not diplayed at all, we're done
948 computePositionedState(pos, states);
950 SymbolDefVector rules;
951 findRules(type, states, rules);
953 return; // no rules matched, we can skip this item
956 SGPropertyNode_ptr vars(new SGPropertyNode);
958 computePositionedPropsAndHeading(pos, vars, heading);
960 osg::Vec2 projected = projectGeod(pos->geod());
961 BOOST_FOREACH(SymbolDef* r, rules) {
962 addSymbolInstance(projected, heading, r, vars);
966 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
968 nd->setStringValue("id", pos->ident());
969 nd->setStringValue("name", pos->name());
970 nd->setDoubleValue("elevation-ft", pos->elevation());
971 nd->setIntValue("heading-deg", 0);
973 switch (pos->type()) {
974 case FGPositioned::VOR:
975 case FGPositioned::LOC:
976 case FGPositioned::TACAN: {
977 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
978 nd->setDoubleValue("frequency-mhz", nav->get_freq());
980 if (pos == _nav1Station) {
981 nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
982 } else if (pos == _nav2Station) {
983 nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
989 case FGPositioned::AIRPORT:
990 case FGPositioned::SEAPORT:
991 case FGPositioned::HELIPORT:
995 case FGPositioned::RUNWAY: {
996 FGRunway* rwy = static_cast<FGRunway*>(pos);
997 nd->setDoubleValue("heading-deg", rwy->headingDeg());
998 nd->setIntValue("length-ft", rwy->lengthFt());
999 nd->setStringValue("airport", rwy->airport()->ident());
1008 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1010 if (_routeSources.count(pos) != 0) {
1011 states.insert("on-active-route");
1014 switch (pos->type()) {
1015 case FGPositioned::VOR:
1016 case FGPositioned::LOC:
1017 if (pos == _nav1Station) {
1018 states.insert("tuned");
1019 states.insert("nav1");
1022 if (pos == _nav2Station) {
1023 states.insert("tuned");
1024 states.insert("nav2");
1028 case FGPositioned::AIRPORT:
1029 case FGPositioned::SEAPORT:
1030 case FGPositioned::HELIPORT:
1032 // once the FMS system has some way to tell us about them, of course
1034 if (pos == _route->departureAirport()) {
1035 states.insert("departure");
1038 if (pos == _route->destinationAirport()) {
1039 states.insert("destination");
1043 case FGPositioned::RUNWAY:
1044 if (pos == _route->departureRunway()) {
1045 states.insert("departure");
1048 if (pos == _route->destinationRunway()) {
1049 states.insert("destination");
1053 case FGPositioned::OBSTACLE:
1055 FGObstacle* obs = (FGObstacle*) pos;
1057 states.insert("lit");
1060 if (obj->getHeightAGLFt() >= 1000) {
1061 states.insert("greater-1000-ft");
1068 } // FGPositioned::Type switch
1071 void NavDisplay::processAI()
1073 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1074 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1075 SGPropertyNode *model = ai->getChild(i);
1076 if (!model->nChildren()) {
1080 // prefix types with 'ai-', to avoid any chance of namespace collisions
1081 // with fg-positioned.
1083 computeAIStates(model, ss);
1084 SymbolDefVector rules;
1085 findRules(string("ai-") + model->getName(), ss, rules);
1086 if (rules.empty()) {
1087 return; // no rules matched, we can skip this item
1090 double heading = model->getDoubleValue("orientation/true-heading-deg");
1091 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1092 model->getDoubleValue("position/latitude-deg"),
1093 model->getDoubleValue("position/altitude-ft"));
1094 // compute some additional props
1095 int fl = (aiModelPos.getElevationFt() / 1000);
1096 model->setIntValue("flight-level", fl * 10);
1098 osg::Vec2 projected = projectGeod(aiModelPos);
1099 BOOST_FOREACH(SymbolDef* r, rules) {
1100 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1102 } // of ai models iteration
1105 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1107 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1108 if (threatLevel >= 0) {
1109 states.insert("tcas");
1110 // states.insert("tcas-threat-level-" + itoa(threatLevel));
1113 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1114 if (vspeed < -3.0) {
1115 states.insert("descending");
1116 } else if (vspeed > 3.0) {
1117 states.insert("climbing");
1121 void NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1123 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1124 _symbols.push_back(sym);