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 class NavDisplay::CacheListener : public SGPropertyChangeListener
151 CacheListener(NavDisplay *nd) :
155 virtual void valueChanged (SGPropertyNode * prop)
157 _nd->invalidatePositionedCache();
158 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache");
164 ///////////////////////////////////////////////////////////////////
173 bool initFromNode(SGPropertyNode* node)
175 type = node->getStringValue("type");
176 SGPropertyNode* enableNode = node->getChild("enable");
178 enable = sgReadCondition(fgGetNode("/"), enableNode);
182 while (node->hasChild("state", n)) {
183 string m = node->getChild("state", n++)->getStringValue();
185 excluded_states.insert(m.substr(1));
187 required_states.insert(m);
189 } // of matches parsing
191 if (node->hasChild("width")) {
192 float w = node->getFloatValue("width");
193 float h = node->getFloatValue("height", w);
199 xy0.x() = node->getFloatValue("x0", 0.0);
200 xy0.y() = node->getFloatValue("y0", 0.0);
201 xy1.x() = node->getFloatValue("x1", 5);
202 xy1.y() = node->getFloatValue("y1", 5);
205 double texSize = node->getFloatValue("texture-size", 1.0);
207 uv0.x() = node->getFloatValue("u0", 0) / texSize;
208 uv0.y() = node->getFloatValue("v0", 0) / texSize;
209 uv1.x() = node->getFloatValue("u1", 1) / texSize;
210 uv1.y() = node->getFloatValue("v1", 1) / texSize;
212 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
213 priority = node->getIntValue("priority", 0);
214 zOrder = node->getIntValue("zOrder", 0);
215 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
216 roundPos = node->getBoolValue("round-position", true);
218 if (node->hasChild("text")) {
220 alignment = readAlignment(node->getStringValue("text-align"));
221 textTemplate = node->getStringValue("text");
222 textOffset.x() = node->getFloatValue("text-offset-x", 0);
223 textOffset.y() = node->getFloatValue("text-offset-y", 0);
224 textColor = readColor(node->getChild("text-color"), color);
227 drawLine = node->getBoolValue("draw-line", false);
228 lineColor = readColor(node->getChild("line-color"), color);
229 drawRouteLeg = node->getBoolValue("draw-leg", false);
231 stretchSymbol = node->getBoolValue("stretch-symbol", false);
233 stretchY2 = node->getFloatValue("y2");
234 stretchY3 = node->getFloatValue("y3");
235 stretchV2 = node->getFloatValue("v2");
236 stretchV3 = node->getFloatValue("v3");
243 bool enabled; // cached enabled state
246 string_set required_states;
247 string_set excluded_states;
255 bool rotateToHeading;
256 bool roundPos; ///< should position be rounded to integer values
259 osg::Vec2 textOffset;
260 osgText::Text::AlignmentType alignment;
266 // symbol stretching creates three quads (instead of one) - a start,
267 // middle and end quad, positioned along the line of the symbol.
268 // X (and U) axis values determined by the values above, so we only need
269 // to define the Y (and V) values to build the other quads.
271 double stretchY2, stretchY3;
272 double stretchV2, stretchV3;
276 bool matches(const string_set& states) const
278 BOOST_FOREACH(const string& s, required_states) {
279 if (states.count(s) == 0) {
284 BOOST_FOREACH(const string& s, excluded_states) {
285 if (states.count(s) != 0) {
297 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
304 osg::Vec2 pos; // projected position
307 SymbolDef* definition;
308 SGPropertyNode_ptr props;
312 assert(definition->hasText);
317 size_t pos = definition->textTemplate.find('{', lastPos);
318 if (pos == string::npos) { // no more replacements
319 r.append(definition->textTemplate.substr(lastPos));
323 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
325 size_t endReplacement = definition->textTemplate.find('}', pos+1);
326 if (endReplacement <= pos) {
327 return "bad replacement";
330 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
331 // look for formatter in spec
332 size_t colonPos = spec.find(':');
333 if (colonPos == string::npos) {
334 // simple replacement
335 r.append(props->getStringValue(spec));
337 string format = spec.substr(colonPos + 1);
338 string prop = spec.substr(0, colonPos);
339 r.append(formatPropertyValue(props->getNode(prop), format));
342 lastPos = endReplacement + 1;
349 //////////////////////////////////////////////////////////////////
351 NavDisplay::NavDisplay(SGPropertyNode *node) :
352 _name(node->getStringValue("name", "nd")),
353 _num(node->getIntValue("number", 0)),
355 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
364 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
365 _font_node = _Instrument->getNode("font", true);
367 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
368 INITFONT("name", DEFAULT_FONT, String);
369 INITFONT("size", 8, Float);
370 INITFONT("line-spacing", 0.25, Float);
371 INITFONT("color/red", 0, Float);
372 INITFONT("color/green", 0.8, Float);
373 INITFONT("color/blue", 0, Float);
374 INITFONT("color/alpha", 1, Float);
377 SGPropertyNode* symbolsNode = node->getNode("symbols");
378 SGPropertyNode* symbol;
380 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
381 SymbolDef* def = new SymbolDef;
382 if (!def->initFromNode(symbol)) {
387 _rules.push_back(def);
388 } // of symbol definition parsing
392 NavDisplay::~NavDisplay()
400 _cachedItemsValid = false;
401 _cacheListener.reset(new CacheListener(this));
403 _serviceable_node = _Instrument->getNode("serviceable", true);
404 _rangeNode = _Instrument->getNode("range", true);
405 _rangeNode->setDoubleValue(40.0);
406 _rangeNode->addChangeListener(_cacheListener.get());
408 // texture name to use in 2D and 3D instruments
409 _texture_path = _Instrument->getStringValue("radar-texture-path",
410 "Aircraft/Instruments/Textures/od_wxradar.rgb");
411 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
413 string path = _Instrument->getStringValue("symbol-texture-path",
414 "Aircraft/Instruments/Textures/nd-symbols.png");
415 SGPath tpath = globals->resolve_aircraft_path(path);
416 if (!tpath.exists()) {
417 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
420 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
421 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
423 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
424 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
425 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
427 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
429 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
430 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
432 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
433 _excessDataNode->setBoolValue(false);
435 // OSG geometry setup
436 _radarGeode = new osg::Geode;
438 _geom = new osg::Geometry;
439 _geom->setUseDisplayList(false);
441 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
442 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
444 // Initially allocate space for 128 quads
445 _vertices = new osg::Vec2Array;
446 _vertices->setDataVariance(osg::Object::DYNAMIC);
447 _vertices->reserve(128 * 4);
448 _geom->setVertexArray(_vertices);
449 _texCoords = new osg::Vec2Array;
450 _texCoords->setDataVariance(osg::Object::DYNAMIC);
451 _texCoords->reserve(128 * 4);
452 _geom->setTexCoordArray(0, _texCoords);
454 _quadColors = new osg::Vec4Array;
455 _quadColors->setDataVariance(osg::Object::DYNAMIC);
456 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
457 _geom->setColorArray(_quadColors);
459 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
460 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
461 _geom->addPrimitiveSet(_symbolPrimSet);
463 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
464 osg::Vec3f(256.0f, 256.0f, 0.0f)));
466 _radarGeode->addDrawable(_geom);
468 // Texture in the 2D panel system
469 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
471 _lineGeometry = new osg::Geometry;
472 _lineGeometry->setUseDisplayList(false);
473 stateSet = _lineGeometry->getOrCreateStateSet();
474 osg::LineWidth *lw = new osg::LineWidth();
476 stateSet->setAttribute(lw);
478 _lineVertices = new osg::Vec2Array;
479 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
480 _lineVertices->reserve(128 * 4);
481 _lineGeometry->setVertexArray(_lineVertices);
484 _lineColors = new osg::Vec4Array;
485 _lineColors->setDataVariance(osg::Object::DYNAMIC);
486 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
487 _lineGeometry->setColorArray(_lineColors);
489 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
490 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
491 _lineGeometry->addPrimitiveSet(_linePrimSet);
493 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
494 osg::Vec3f(256.0f, 256.0f, 0.0f)));
496 _radarGeode->addDrawable(_lineGeometry);
498 _textGeode = new osg::Geode;
500 osg::Camera *camera = _odg->getCamera();
501 camera->addChild(_radarGeode.get());
502 camera->addChild(_textGeode.get());
503 osg::Texture2D* tex = _odg->getTexture();
504 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
505 0, tex->getTextureHeight());
511 NavDisplay::update (double delta_time_sec)
513 if (!fgGetBool("sim/sceneryloaded", false)) {
517 if (!_odg || !_serviceable_node->getBoolValue()) {
518 _Instrument->setStringValue("status", "");
522 _time += delta_time_sec;
523 if (_time < _updateInterval){
526 _time -= _updateInterval;
528 _rangeNm = _rangeNode->getFloatValue();
529 if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
530 _view_heading = fgGetDouble("/orientation/heading-deg");
532 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
535 _scale = _odg->size() / _rangeNm;
537 double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
538 double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
539 _centerTrans = osg::Matrixf::translate(xCenterFrac * _odg->size(),
540 yCenterFrac * _odg->size(), 0.0);
542 // scale from nm to display units, rotate so aircraft heading is up
543 // (as opposed to north), and compensate for centering
544 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
545 degRotation(-_view_heading) * _centerTrans;
547 _pos = globals->get_aircraft_position();
549 // invalidate the cache of positioned items, if we travelled more than 1nm
550 if (_cachedItemsValid) {
551 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
552 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
553 _cachedItemsValid = (movedNm < 1.0);
554 if (!_cachedItemsValid) {
555 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache due to moving: " << movedNm);
560 _lineVertices->clear();
561 _lineColors->clear();
562 _quadColors->clear();
564 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
566 BOOST_FOREACH(SymbolInstance* si, _symbols) {
571 BOOST_FOREACH(SymbolDef* def, _rules) {
573 def->enabled = def->enable->test();
583 limitDisplayedSymbols();
586 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
587 _symbolPrimSet->dirty();
588 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
589 _linePrimSet->dirty();
594 NavDisplay::updateFont()
596 float red = _font_node->getFloatValue("color/red");
597 float green = _font_node->getFloatValue("color/green");
598 float blue = _font_node->getFloatValue("color/blue");
599 float alpha = _font_node->getFloatValue("color/alpha");
600 _font_color.set(red, green, blue, alpha);
602 _font_size = _font_node->getFloatValue("size");
603 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
604 string path = _font_node->getStringValue("name", DEFAULT_FONT);
607 if (path[0] != '/') {
608 tpath = globals->get_fg_root();
609 tpath.append("Fonts");
615 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
616 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
620 _font->setMinFilterHint(osg::Texture::NEAREST);
621 _font->setMagFilterHint(osg::Texture::NEAREST);
622 _font->setGlyphImageMargin(0);
623 _font->setGlyphImageMarginRatio(0);
627 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
629 SymbolDef* def = sym->definition;
633 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
635 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
637 if (def->rotateToHeading) {
638 osg::Matrixf m(degRotation(sym->headingDeg));
639 for (int i=0; i<4; ++i) {
640 verts[i] = mult(verts[i], m);
644 osg::Vec2 pos = sym->pos;
646 pos = osg::Vec2((int) pos.x(), (int) pos.y());
649 _texCoords->push_back(def->uv0);
650 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
651 _texCoords->push_back(def->uv1);
652 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
654 for (int i=0; i<4; ++i) {
655 _vertices->push_back(verts[i] + pos);
656 _quadColors->push_back(def->color);
659 if (def->stretchSymbol) {
660 osg::Vec2 stretchVerts[4];
661 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
662 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
663 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
664 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
666 osg::Matrixf m(degRotation(sym->headingDeg));
667 for (int i=0; i<4; ++i) {
668 stretchVerts[i] = mult(stretchVerts[i], m);
672 _vertices->push_back(verts[2] + pos);
673 _vertices->push_back(stretchVerts[1] + sym->endPos);
674 _vertices->push_back(stretchVerts[0] + sym->endPos);
675 _vertices->push_back(verts[3] + pos);
677 _texCoords->push_back(def->uv1);
678 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
679 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
680 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
682 for (int i=0; i<4; ++i) {
683 _quadColors->push_back(def->color);
686 // quad three, for the end portion
687 for (int i=0; i<4; ++i) {
688 _vertices->push_back(stretchVerts[i] + sym->endPos);
689 _quadColors->push_back(def->color);
692 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
693 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
694 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
695 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
699 addLine(sym->pos, sym->endPos, def->lineColor);
706 osgText::Text* t = new osgText::Text;
707 t->setFont(_font.get());
708 t->setFontResolution(12, 12);
709 t->setCharacterSize(_font_size);
710 t->setLineSpacing(_font_spacing);
711 t->setColor(def->textColor);
712 t->setAlignment(def->alignment);
713 t->setText(sym->text());
716 osg::Vec2 textPos = def->textOffset + pos;
717 // ensure we use ints here, or text visual quality goes bad
718 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
719 _textGeode->addDrawable(t);
722 class OrderByPriority
725 bool operator()(SymbolInstance* a, SymbolInstance* b)
727 return a->definition->priority > b->definition->priority;
731 void NavDisplay::limitDisplayedSymbols()
733 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
734 if (_symbols.size() <= maxSymbols) {
735 _excessDataNode->setBoolValue(false);
739 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
740 _symbols.resize(maxSymbols);
741 _excessDataNode->setBoolValue(true);
747 bool operator()(SymbolInstance* a, SymbolInstance* b)
749 return a->definition->zOrder > b->definition->zOrder;
753 void NavDisplay::addSymbolsToScene()
755 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
756 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
757 addSymbolToScene(sym);
761 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
763 _lineVertices->push_back(a);
764 _lineVertices->push_back(b);
765 _lineColors->push_back(color);
766 _lineColors->push_back(color);
769 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
771 osg::Vec3 p(0, rangeNm, 0.0);
772 p = degRotation(bearingDeg).preMult(p);
773 p = _projectMat.preMult(p);
774 return osg::Vec2(p.x(), p.y());
777 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
779 double rangeM, bearing, az2;
780 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
781 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
784 class Filter : public FGPositioned::Filter
787 double minRunwayLengthFt;
789 virtual bool pass(FGPositioned* aPos) const
791 if (aPos->type() == FGPositioned::FIX) {
792 string ident(aPos->ident());
793 // ignore fixes which end in digits
794 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
799 if (aPos->type() == FGPositioned::AIRPORT) {
800 FGAirport* apt = (FGAirport*) aPos;
801 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
809 virtual FGPositioned::Type minType() const {
810 return FGPositioned::AIRPORT;
813 virtual FGPositioned::Type maxType() const {
814 return FGPositioned::OBSTACLE;
818 void NavDisplay::findItems()
820 if (!_cachedItemsValid) {
821 SG_LOG(SG_INSTR, SG_INFO, "re-validating NavDisplay cache");
823 filt.minRunwayLengthFt = 2000;
824 _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
825 _cachedItemsValid = true;
826 _cachedPos = SGVec3d::fromGeod(_pos);
829 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
830 foundPositionedItem(pos);
834 void NavDisplay::processRoute()
836 _routeSources.clear();
837 RoutePath path(_route->waypts());
838 int current = _route->currentIndex();
840 for (int w=0; w<_route->numWaypts(); ++w) {
841 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
842 _routeSources.insert(wpt->source());
845 state.insert("on-active-route");
848 state.insert("passed");
852 state.insert("current-wp");
856 state.insert("future");
859 if (w == (current + 1)) {
860 state.insert("next-wp");
863 SymbolDefVector rules;
864 findRules("waypoint" , state, rules);
866 return; // no rules matched, we can skip this item
869 SGGeod g = path.positionForIndex(w);
870 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
872 computeWayptPropsAndHeading(wpt, g, vars, heading);
874 osg::Vec2 projected = projectGeod(g);
875 BOOST_FOREACH(SymbolDef* r, rules) {
876 addSymbolInstance(projected, heading, r, vars);
878 if (r->drawRouteLeg) {
879 SGGeodVec gv(path.pathForIndex(w));
881 osg::Vec2 pr = projectGeod(gv[0]);
882 for (unsigned int i=1; i<gv.size(); ++i) {
883 osg::Vec2 p = projectGeod(gv[i]);
884 addLine(pr, p, r->lineColor);
888 } // of leg drawing enabled
889 } // of matching rules iteration
890 } // of waypoints iteration
893 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
896 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
897 nd->setIntValue("radial", heading);
898 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
900 heading = nd->getDoubleValue("leg-bearing-true-deg");
903 void NavDisplay::processNavRadios()
905 _nav1Station = processNavRadio(_navRadio1Node);
906 _nav2Station = processNavRadio(_navRadio2Node);
908 foundPositionedItem(_nav1Station);
909 foundPositionedItem(_nav2Station);
912 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
914 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
915 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
916 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
917 // station was not found
925 bool NavDisplay::anyRuleForType(const string& type) const
927 BOOST_FOREACH(SymbolDef* r, _rules) {
932 if (r->type == type) {
940 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
942 BOOST_FOREACH(SymbolDef* r, _rules) {
943 if (!r->enabled || (r->type != type)) {
947 if (r->matches(states)) {
950 } // of rules iteration
955 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
957 BOOST_FOREACH(SymbolDef* candidate, _rules) {
958 if (!candidate->enabled || (candidate->type != type)) {
962 if (candidate->matches(states)) {
963 rules.push_back(candidate);
968 void NavDisplay::foundPositionedItem(FGPositioned* pos)
974 string type = FGPositioned::nameForType(pos->type());
975 if (!anyRuleForType(type)) {
976 return; // not diplayed at all, we're done
980 computePositionedState(pos, states);
982 SymbolDefVector rules;
983 findRules(type, states, rules);
985 return; // no rules matched, we can skip this item
988 SGPropertyNode_ptr vars(new SGPropertyNode);
990 computePositionedPropsAndHeading(pos, vars, heading);
992 osg::Vec2 projected = projectGeod(pos->geod());
993 BOOST_FOREACH(SymbolDef* r, rules) {
994 addSymbolInstance(projected, heading, r, vars);
998 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1000 nd->setStringValue("id", pos->ident());
1001 nd->setStringValue("name", pos->name());
1002 nd->setDoubleValue("elevation-ft", pos->elevation());
1003 nd->setIntValue("heading-deg", 0);
1005 switch (pos->type()) {
1006 case FGPositioned::VOR:
1007 case FGPositioned::LOC:
1008 case FGPositioned::TACAN: {
1009 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1010 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1012 if (pos == _nav1Station) {
1013 nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
1014 } else if (pos == _nav2Station) {
1015 nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
1021 case FGPositioned::AIRPORT:
1022 case FGPositioned::SEAPORT:
1023 case FGPositioned::HELIPORT:
1027 case FGPositioned::RUNWAY: {
1028 FGRunway* rwy = static_cast<FGRunway*>(pos);
1029 nd->setDoubleValue("heading-deg", rwy->headingDeg());
1030 nd->setIntValue("length-ft", rwy->lengthFt());
1031 nd->setStringValue("airport", rwy->airport()->ident());
1040 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1042 if (_routeSources.count(pos) != 0) {
1043 states.insert("on-active-route");
1046 switch (pos->type()) {
1047 case FGPositioned::VOR:
1048 case FGPositioned::LOC:
1049 if (pos == _nav1Station) {
1050 states.insert("tuned");
1051 states.insert("nav1");
1054 if (pos == _nav2Station) {
1055 states.insert("tuned");
1056 states.insert("nav2");
1060 case FGPositioned::AIRPORT:
1061 case FGPositioned::SEAPORT:
1062 case FGPositioned::HELIPORT:
1064 // once the FMS system has some way to tell us about them, of course
1066 if (pos == _route->departureAirport()) {
1067 states.insert("departure");
1070 if (pos == _route->destinationAirport()) {
1071 states.insert("destination");
1075 case FGPositioned::RUNWAY:
1076 if (pos == _route->departureRunway()) {
1077 states.insert("departure");
1080 if (pos == _route->destinationRunway()) {
1081 states.insert("destination");
1085 case FGPositioned::OBSTACLE:
1087 FGObstacle* obs = (FGObstacle*) pos;
1089 states.insert("lit");
1092 if (obj->getHeightAGLFt() >= 1000) {
1093 states.insert("greater-1000-ft");
1100 } // FGPositioned::Type switch
1103 void NavDisplay::processAI()
1105 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1106 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1107 SGPropertyNode *model = ai->getChild(i);
1108 if (!model->nChildren()) {
1112 // prefix types with 'ai-', to avoid any chance of namespace collisions
1113 // with fg-positioned.
1115 computeAIStates(model, ss);
1116 SymbolDefVector rules;
1117 findRules(string("ai-") + model->getName(), ss, rules);
1118 if (rules.empty()) {
1119 return; // no rules matched, we can skip this item
1122 double heading = model->getDoubleValue("orientation/true-heading-deg");
1123 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1124 model->getDoubleValue("position/latitude-deg"),
1125 model->getDoubleValue("position/altitude-ft"));
1126 // compute some additional props
1127 int fl = (aiModelPos.getElevationFt() / 1000);
1128 model->setIntValue("flight-level", fl * 10);
1130 osg::Vec2 projected = projectGeod(aiModelPos);
1131 BOOST_FOREACH(SymbolDef* r, rules) {
1132 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1134 } // of ai models iteration
1137 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1139 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1140 if (threatLevel >= 0) {
1141 states.insert("tcas");
1142 // states.insert("tcas-threat-level-" + itoa(threatLevel));
1145 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1146 if (vspeed < -3.0) {
1147 states.insert("descending");
1148 } else if (vspeed > 3.0) {
1149 states.insert("climbing");
1153 bool NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1155 if (isProjectedClipped(proj)) {
1159 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1160 _symbols.push_back(sym);
1164 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1166 double size = _odg->size();
1167 return (projected.x() < 0.0) ||
1168 (projected.y() < 0.0) ||
1169 (projected.x() >= size) ||
1170 (projected.y() >= size);