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/misc/strutils.hxx>
46 #include <simgear/math/sg_geodesy.hxx>
50 #include <iostream> // for cout, endl
52 using std::stringstream;
54 using std::setprecision;
63 #include <Main/fg_props.hxx>
64 #include <Main/globals.hxx>
65 #include <Cockpit/panel.hxx>
66 #include <Navaids/routePath.hxx>
67 #include <Autopilot/route_mgr.hxx>
68 #include <Navaids/navrecord.hxx>
69 #include <Navaids/navlist.hxx>
70 #include <Navaids/fix.hxx>
71 #include <Airports/simple.hxx>
72 #include <Airports/runways.hxx>
74 #include "instrument_mgr.hxx"
75 #include "od_gauge.hxx"
77 static const char *DEFAULT_FONT = "typewriter.txf";
80 osg::Matrixf degRotation(float angle)
82 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
85 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
88 result.r() = colorNode->getDoubleValue("red", c.r());
89 result.g() = colorNode->getDoubleValue("green", c.g());
90 result.b() = colorNode->getDoubleValue("blue", c.b());
91 result.a() = colorNode->getDoubleValue("alpha", c.a());
95 static osgText::Text::AlignmentType readAlignment(const std::string& t)
97 if (t == "left-top") {
98 return osgText::Text::LEFT_TOP;
99 } else if (t == "left-center") {
100 return osgText::Text::LEFT_CENTER;
101 } else if (t == "left-bottom") {
102 return osgText::Text::LEFT_BOTTOM;
103 } else if (t == "center-top") {
104 return osgText::Text::CENTER_TOP;
105 } else if (t == "center-center") {
106 return osgText::Text::CENTER_CENTER;
107 } else if (t == "center-bottom") {
108 return osgText::Text::CENTER_BOTTOM;
109 } else if (t == "right-top") {
110 return osgText::Text::RIGHT_TOP;
111 } else if (t == "right-center") {
112 return osgText::Text::RIGHT_CENTER;
113 } else if (t == "right-bottom") {
114 return osgText::Text::RIGHT_BOTTOM;
115 } else if (t == "left-baseline") {
116 return osgText::Text::LEFT_BASE_LINE;
117 } else if (t == "center-baseline") {
118 return osgText::Text::CENTER_BASE_LINE;
119 } else if (t == "right-baseline") {
120 return osgText::Text::RIGHT_BASE_LINE;
123 return osgText::Text::BASE_LINE;
126 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
129 static char buf[512];
130 if (format.find('d') != string::npos) {
131 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
135 if (format.find('s') != string::npos) {
136 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
140 // assume it's a double/float
141 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
145 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
147 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
148 return osg::Vec2(r.x(), r.y());
151 class NavDisplay::CacheListener : public SGPropertyChangeListener
154 CacheListener(NavDisplay *nd) :
158 virtual void valueChanged (SGPropertyNode * prop)
160 _nd->invalidatePositionedCache();
161 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache");
167 class NavDisplay::ForceUpdateListener : public SGPropertyChangeListener
170 ForceUpdateListener(NavDisplay *nd) :
174 virtual void valueChanged (SGPropertyNode * prop)
176 SG_LOG(SG_INSTR, SG_INFO, "forcing NavDisplay update");
183 ///////////////////////////////////////////////////////////////////
193 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
195 if (!node->getChild("type")) {
199 type = node->getStringValue("type");
200 SGPropertyNode* enableNode = node->getChild("enable");
202 enable.reset(sgReadCondition(fgGetNode("/"), enableNode));
206 while (node->hasChild("state", n)) {
207 string m = node->getChild("state", n++)->getStringValue();
209 excluded_states.insert(m.substr(1));
211 required_states.insert(m);
213 } // of matches parsing
218 void setDefinition(SymbolDef* d)
223 SymbolDef* getDefinition() const
224 { return definition; }
226 bool matches(const string_set& states) const
228 BOOST_FOREACH(const string& s, required_states) {
229 if (states.count(s) == 0) {
234 BOOST_FOREACH(const string& s, excluded_states) {
235 if (states.count(s) != 0) {
246 enabled = enable->test();
252 bool enabled; // cached enabled state
255 SymbolDef* definition;
257 std::auto_ptr<SGCondition> enable;
258 string_set required_states;
259 string_set excluded_states;
266 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
268 if (node->getChild("type")) {
269 SymbolRule* builtinRule = new SymbolRule;
270 builtinRule->initFromNode(node, owner);
271 builtinRule->setDefinition(this);
272 owner->addRule(builtinRule);
275 if (node->hasChild("width")) {
276 float w = node->getFloatValue("width");
277 float h = node->getFloatValue("height", w);
283 xy0.x() = node->getFloatValue("x0", 0.0);
284 xy0.y() = node->getFloatValue("y0", 0.0);
285 xy1.x() = node->getFloatValue("x1", 5);
286 xy1.y() = node->getFloatValue("y1", 5);
289 double texSize = node->getFloatValue("texture-size", owner->textureSize());
291 uv0.x() = node->getFloatValue("u0", 0) / texSize;
292 uv0.y() = node->getFloatValue("v0", 0) / texSize;
293 uv1.x() = node->getFloatValue("u1", 1) / texSize;
294 uv1.y() = node->getFloatValue("v1", 1) / texSize;
296 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
297 priority = node->getIntValue("priority", 0);
298 zOrder = node->getIntValue("zOrder", 0);
299 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
300 roundPos = node->getBoolValue("round-position", true);
302 if (node->hasChild("text")) {
304 alignment = readAlignment(node->getStringValue("text-align"));
305 textTemplate = node->getStringValue("text");
306 textOffset.x() = node->getFloatValue("text-offset-x", 0);
307 textOffset.y() = node->getFloatValue("text-offset-y", 0);
308 textColor = readColor(node->getChild("text-color"), color);
311 drawLine = node->getBoolValue("draw-line", false);
312 lineColor = readColor(node->getChild("line-color"), color);
313 drawRouteLeg = node->getBoolValue("draw-leg", false);
315 stretchSymbol = node->getBoolValue("stretch-symbol", false);
317 stretchY2 = node->getFloatValue("y2");
318 stretchY3 = node->getFloatValue("y3");
319 stretchV2 = node->getFloatValue("v2") / texSize;
320 stretchV3 = node->getFloatValue("v3") / texSize;
332 bool rotateToHeading;
333 bool roundPos; ///< should position be rounded to integer values
336 osg::Vec2 textOffset;
337 osgText::Text::AlignmentType alignment;
343 // symbol stretching creates three quads (instead of one) - a start,
344 // middle and end quad, positioned along the line of the symbol.
345 // X (and U) axis values determined by the values above, so we only need
346 // to define the Y (and V) values to build the other quads.
348 double stretchY2, stretchY3;
349 double stretchV2, stretchV3;
358 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
365 osg::Vec2 pos; // projected position
368 SymbolDef* definition;
369 SGPropertyNode_ptr props;
373 assert(definition->hasText);
378 size_t pos = definition->textTemplate.find('{', lastPos);
379 if (pos == string::npos) { // no more replacements
380 r.append(definition->textTemplate.substr(lastPos));
384 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
386 size_t endReplacement = definition->textTemplate.find('}', pos+1);
387 if (endReplacement <= pos) {
388 return "bad replacement";
391 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
392 // look for formatter in spec
393 size_t colonPos = spec.find(':');
394 if (colonPos == string::npos) {
395 // simple replacement
396 r.append(props->getStringValue(spec));
398 string format = spec.substr(colonPos + 1);
399 string prop = spec.substr(0, colonPos);
400 r.append(formatPropertyValue(props->getNode(prop), format));
403 lastPos = endReplacement + 1;
410 //////////////////////////////////////////////////////////////////
412 NavDisplay::NavDisplay(SGPropertyNode *node) :
413 _name(node->getStringValue("name", "nd")),
414 _num(node->getIntValue("number", 0)),
416 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
426 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
427 _font_node = _Instrument->getNode("font", true);
429 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
430 INITFONT("name", DEFAULT_FONT, String);
431 INITFONT("size", 8, Float);
432 INITFONT("line-spacing", 0.25, Float);
433 INITFONT("color/red", 0, Float);
434 INITFONT("color/green", 0.8, Float);
435 INITFONT("color/blue", 0, Float);
436 INITFONT("color/alpha", 1, Float);
439 _textureSize = _Instrument->getNode("symbol-teture-size", true)->getIntValue();
440 SGPropertyNode* symbolsNode = node->getNode("symbols");
441 SGPropertyNode* symbol;
443 map<string, SymbolDef*> definitionDict;
444 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
445 SymbolDef* def = new SymbolDef;
446 if (!def->initFromNode(symbol, this)) {
451 const char* id = symbol->getStringValue("id");
452 if (id && strlen(id)) {
453 definitionDict[id] = def;
456 _definitions.push_back(def);
457 } // of symbol definition parsing
459 SGPropertyNode* rulesNode = node->getNode("rules");
461 SGPropertyNode* rule;
463 for (int i = 0; (rule = rulesNode->getChild("rule", i)) != NULL; ++i) {
464 SymbolRule* r = new SymbolRule;
465 if (!r->initFromNode(rule, this)) {
470 const char* id = symbol->getStringValue("symbol");
471 if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
472 r->setDefinition(definitionDict[id]);
474 SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
480 } // of symbol rule parsing
486 NavDisplay::~NavDisplay()
494 _cachedItemsValid = false;
495 _cacheListener.reset(new CacheListener(this));
496 _forceUpdateListener.reset(new ForceUpdateListener(this));
498 _serviceable_node = _Instrument->getNode("serviceable", true);
499 _rangeNode = _Instrument->getNode("range", true);
500 _rangeNode->setDoubleValue(40.0);
501 _rangeNode->addChangeListener(_cacheListener.get());
502 _rangeNode->addChangeListener(_forceUpdateListener.get());
504 _xCenterNode = _Instrument->getNode("x-center");
505 _xCenterNode->setDoubleValue(0.5);
506 _xCenterNode->addChangeListener(_forceUpdateListener.get());
507 _yCenterNode = _Instrument->getNode("y-center");
508 _yCenterNode->setDoubleValue(0.5);
509 _yCenterNode->addChangeListener(_forceUpdateListener.get());
511 // texture name to use in 2D and 3D instruments
512 _texture_path = _Instrument->getStringValue("radar-texture-path",
513 "Aircraft/Instruments/Textures/od_wxradar.rgb");
514 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
516 string path = _Instrument->getStringValue("symbol-texture-path",
517 "Aircraft/Instruments/Textures/nd-symbols.png");
518 SGPath tpath = globals->resolve_aircraft_path(path);
519 if (!tpath.exists()) {
520 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
523 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
524 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
526 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
527 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
528 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
530 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
532 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
533 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
535 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
536 _excessDataNode->setBoolValue(false);
537 _testModeNode = _Instrument->getChild("test-mode", 0, true);
538 _testModeNode->setBoolValue(false);
540 // OSG geometry setup
541 _radarGeode = new osg::Geode;
543 _geom = new osg::Geometry;
544 _geom->setUseDisplayList(false);
546 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
547 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
548 stateSet->setDataVariance(osg::Object::STATIC);
550 // Initially allocate space for 128 quads
551 _vertices = new osg::Vec2Array;
552 _vertices->setDataVariance(osg::Object::DYNAMIC);
553 _vertices->reserve(128 * 4);
554 _geom->setVertexArray(_vertices);
555 _texCoords = new osg::Vec2Array;
556 _texCoords->setDataVariance(osg::Object::DYNAMIC);
557 _texCoords->reserve(128 * 4);
558 _geom->setTexCoordArray(0, _texCoords);
560 _quadColors = new osg::Vec4Array;
561 _quadColors->setDataVariance(osg::Object::DYNAMIC);
562 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
563 _geom->setColorArray(_quadColors);
565 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
566 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
567 _geom->addPrimitiveSet(_symbolPrimSet);
569 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
570 osg::Vec3f(256.0f, 256.0f, 0.0f)));
572 _radarGeode->addDrawable(_geom);
574 // Texture in the 2D panel system
575 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
577 _lineGeometry = new osg::Geometry;
578 _lineGeometry->setUseDisplayList(false);
579 stateSet = _lineGeometry->getOrCreateStateSet();
580 osg::LineWidth *lw = new osg::LineWidth();
582 stateSet->setAttribute(lw);
584 _lineVertices = new osg::Vec2Array;
585 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
586 _lineVertices->reserve(128 * 4);
587 _lineGeometry->setVertexArray(_lineVertices);
590 _lineColors = new osg::Vec4Array;
591 _lineColors->setDataVariance(osg::Object::DYNAMIC);
592 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
593 _lineGeometry->setColorArray(_lineColors);
595 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
596 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
597 _lineGeometry->addPrimitiveSet(_linePrimSet);
599 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
600 osg::Vec3f(256.0f, 256.0f, 0.0f)));
602 _radarGeode->addDrawable(_lineGeometry);
604 _textGeode = new osg::Geode;
606 osg::Camera *camera = _odg->getCamera();
607 camera->addChild(_radarGeode.get());
608 camera->addChild(_textGeode.get());
609 osg::Texture2D* tex = _odg->getTexture();
610 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
611 0, tex->getTextureHeight());
617 NavDisplay::update (double delta_time_sec)
619 if (!fgGetBool("sim/sceneryloaded", false)) {
623 if (!_odg || !_serviceable_node->getBoolValue()) {
624 _Instrument->setStringValue("status", "");
629 _forceUpdate = false;
632 _time += delta_time_sec;
633 if (_time < _updateInterval){
636 _time -= _updateInterval;
639 _rangeNm = _rangeNode->getFloatValue();
640 if (_testModeNode->getBoolValue()) {
642 } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
643 _view_heading = fgGetDouble("/orientation/heading-deg");
645 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
648 double xCenterFrac = _xCenterNode->getDoubleValue();
649 double yCenterFrac = _yCenterNode->getDoubleValue();
650 int pixelSize = _odg->size();
652 int rangePixels = _Instrument->getIntValue("range-pixels", -1);
653 if (rangePixels < 0) {
654 // hacky - assume (as is very common) that x-frac doesn't vary, and
655 // y-frac is used to position the center at either the top or bottom of
656 // the pixel area. Measure from the center to the furthest edge (top or bottom)
657 rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
660 _scale = rangePixels / _rangeNm;
661 _Instrument->setDoubleValue("scale", _scale);
664 _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize,
665 yCenterFrac * pixelSize, 0.0);
667 // scale from nm to display units, rotate so aircraft heading is up
668 // (as opposed to north), and compensate for centering
669 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
670 degRotation(-_view_heading) * _centerTrans;
672 _pos = globals->get_aircraft_position();
674 // invalidate the cache of positioned items, if we travelled more than 1nm
675 if (_cachedItemsValid) {
676 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
677 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
678 _cachedItemsValid = (movedNm < 1.0);
679 if (!_cachedItemsValid) {
680 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache due to moving: " << movedNm);
685 _lineVertices->clear();
686 _lineColors->clear();
687 _quadColors->clear();
689 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
691 BOOST_FOREACH(SymbolInstance* si, _symbols) {
696 BOOST_FOREACH(SymbolRule* r, _rules) {
700 if (_testModeNode->getBoolValue()) {
707 limitDisplayedSymbols();
712 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
713 _symbolPrimSet->dirty();
714 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
715 _linePrimSet->dirty();
720 NavDisplay::updateFont()
722 float red = _font_node->getFloatValue("color/red");
723 float green = _font_node->getFloatValue("color/green");
724 float blue = _font_node->getFloatValue("color/blue");
725 float alpha = _font_node->getFloatValue("color/alpha");
726 _font_color.set(red, green, blue, alpha);
728 _font_size = _font_node->getFloatValue("size");
729 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
730 string path = _font_node->getStringValue("name", DEFAULT_FONT);
733 if (path[0] != '/') {
734 tpath = globals->get_fg_root();
735 tpath.append("Fonts");
741 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
742 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
746 _font->setMinFilterHint(osg::Texture::NEAREST);
747 _font->setMagFilterHint(osg::Texture::NEAREST);
748 _font->setGlyphImageMargin(0);
749 _font->setGlyphImageMarginRatio(0);
753 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
755 SymbolDef* def = sym->definition;
759 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
761 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
763 if (def->rotateToHeading) {
764 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
765 for (int i=0; i<4; ++i) {
766 verts[i] = mult(verts[i], m);
770 osg::Vec2 pos = sym->pos;
772 pos = osg::Vec2((int) pos.x(), (int) pos.y());
775 _texCoords->push_back(def->uv0);
776 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
777 _texCoords->push_back(def->uv1);
778 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
780 for (int i=0; i<4; ++i) {
781 _vertices->push_back(verts[i] + pos);
782 _quadColors->push_back(def->color);
785 if (def->stretchSymbol) {
786 osg::Vec2 stretchVerts[4];
787 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
788 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
789 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
790 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
792 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
793 for (int i=0; i<4; ++i) {
794 stretchVerts[i] = mult(stretchVerts[i], m);
798 _vertices->push_back(verts[2] + pos);
799 _vertices->push_back(stretchVerts[1] + sym->endPos);
800 _vertices->push_back(stretchVerts[0] + sym->endPos);
801 _vertices->push_back(verts[3] + pos);
803 _texCoords->push_back(def->uv1);
804 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
805 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
806 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
808 for (int i=0; i<4; ++i) {
809 _quadColors->push_back(def->color);
812 // quad three, for the end portion
813 for (int i=0; i<4; ++i) {
814 _vertices->push_back(stretchVerts[i] + sym->endPos);
815 _quadColors->push_back(def->color);
818 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
819 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
820 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
821 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
825 addLine(sym->pos, sym->endPos, def->lineColor);
832 osgText::Text* t = new osgText::Text;
833 t->setFont(_font.get());
834 t->setFontResolution(12, 12);
835 t->setCharacterSize(_font_size);
836 t->setLineSpacing(_font_spacing);
837 t->setColor(def->textColor);
838 t->setAlignment(def->alignment);
839 t->setText(sym->text());
842 osg::Vec2 textPos = def->textOffset + pos;
843 // ensure we use ints here, or text visual quality goes bad
844 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
845 _textGeode->addDrawable(t);
848 class OrderByPriority
851 bool operator()(SymbolInstance* a, SymbolInstance* b)
853 return a->definition->priority > b->definition->priority;
857 void NavDisplay::limitDisplayedSymbols()
859 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
860 if (_symbols.size() <= maxSymbols) {
861 _excessDataNode->setBoolValue(false);
865 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
866 _symbols.resize(maxSymbols);
867 _excessDataNode->setBoolValue(true);
873 bool operator()(SymbolInstance* a, SymbolInstance* b)
875 return a->definition->zOrder > b->definition->zOrder;
879 void NavDisplay::addSymbolsToScene()
881 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
882 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
883 addSymbolToScene(sym);
887 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
889 _lineVertices->push_back(a);
890 _lineVertices->push_back(b);
891 _lineColors->push_back(color);
892 _lineColors->push_back(color);
895 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
897 osg::Vec3 p(0, rangeNm, 0.0);
898 p = degRotation(bearingDeg).preMult(p);
899 p = _projectMat.preMult(p);
900 return osg::Vec2(p.x(), p.y());
903 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
905 double rangeM, bearing, az2;
906 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
907 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
910 class Filter : public FGPositioned::Filter
913 double minRunwayLengthFt;
915 virtual bool pass(FGPositioned* aPos) const
917 if (aPos->type() == FGPositioned::FIX) {
918 string ident(aPos->ident());
919 // ignore fixes which end in digits
920 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
925 if (aPos->type() == FGPositioned::AIRPORT) {
926 FGAirport* apt = (FGAirport*) aPos;
927 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
935 virtual FGPositioned::Type minType() const {
936 return FGPositioned::AIRPORT;
939 virtual FGPositioned::Type maxType() const {
940 return FGPositioned::OBSTACLE;
944 void NavDisplay::findItems()
946 if (!_cachedItemsValid) {
947 SG_LOG(SG_INSTR, SG_INFO, "re-validating NavDisplay cache");
949 filt.minRunwayLengthFt = 2000;
950 _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
951 _cachedItemsValid = true;
952 _cachedPos = SGVec3d::fromGeod(_pos);
955 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
956 foundPositionedItem(pos);
960 void NavDisplay::processRoute()
962 _routeSources.clear();
963 RoutePath path(_route->waypts());
964 int current = _route->currentIndex();
966 for (int w=0; w<_route->numWaypts(); ++w) {
967 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
968 _routeSources.insert(wpt->source());
971 state.insert("on-active-route");
974 state.insert("passed");
978 state.insert("current-wp");
982 state.insert("future");
985 if (w == (current + 1)) {
986 state.insert("next-wp");
989 SymbolRuleVector rules;
990 findRules("waypoint" , state, rules);
992 return; // no rules matched, we can skip this item
995 SGGeod g = path.positionForIndex(w);
996 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
998 computeWayptPropsAndHeading(wpt, g, vars, heading);
1000 osg::Vec2 projected = projectGeod(g);
1001 BOOST_FOREACH(SymbolRule* r, rules) {
1002 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1004 if (r->getDefinition()->drawRouteLeg) {
1005 SGGeodVec gv(path.pathForIndex(w));
1007 osg::Vec2 pr = projectGeod(gv[0]);
1008 for (unsigned int i=1; i<gv.size(); ++i) {
1009 osg::Vec2 p = projectGeod(gv[i]);
1010 addLine(pr, p, r->getDefinition()->lineColor);
1014 } // of leg drawing enabled
1015 } // of matching rules iteration
1016 } // of waypoints iteration
1019 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1022 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1023 nd->setIntValue("radial", heading);
1024 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1026 heading = nd->getDoubleValue("leg-bearing-true-deg");
1029 void NavDisplay::processNavRadios()
1031 _nav1Station = processNavRadio(_navRadio1Node);
1032 _nav2Station = processNavRadio(_navRadio2Node);
1034 foundPositionedItem(_nav1Station);
1035 foundPositionedItem(_nav2Station);
1038 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1040 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1041 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
1042 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1043 // station was not found
1051 bool NavDisplay::anyRuleForType(const string& type) const
1053 BOOST_FOREACH(SymbolRule* r, _rules) {
1058 if (r->type == type) {
1066 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
1068 BOOST_FOREACH(SymbolRule* r, _rules) {
1069 if (!r->enabled || (r->type != type)) {
1073 if (r->matches(states)) {
1076 } // of rules iteration
1081 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1083 BOOST_FOREACH(SymbolRule* candidate, _rules) {
1084 if (!candidate->enabled || (candidate->type != type)) {
1088 if (candidate->matches(states)) {
1089 rules.push_back(candidate);
1094 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1100 string type = FGPositioned::nameForType(pos->type());
1101 if (!anyRuleForType(type)) {
1102 return; // not diplayed at all, we're done
1106 computePositionedState(pos, states);
1108 SymbolRuleVector rules;
1109 findRules(type, states, rules);
1110 if (rules.empty()) {
1111 return; // no rules matched, we can skip this item
1114 SGPropertyNode_ptr vars(new SGPropertyNode);
1116 computePositionedPropsAndHeading(pos, vars, heading);
1118 osg::Vec2 projected = projectGeod(pos->geod());
1119 if (pos->type() == FGPositioned::RUNWAY) {
1120 FGRunway* rwy = (FGRunway*) pos;
1121 projected = projectGeod(rwy->threshold());
1124 BOOST_FOREACH(SymbolRule* r, rules) {
1125 SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1126 if (pos->type() == FGPositioned::RUNWAY) {
1127 FGRunway* rwy = (FGRunway*) pos;
1128 ins->endPos = projectGeod(rwy->end());
1133 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1135 nd->setStringValue("id", pos->ident());
1136 nd->setStringValue("name", pos->name());
1137 nd->setDoubleValue("elevation-ft", pos->elevation());
1138 nd->setIntValue("heading-deg", 0);
1141 switch (pos->type()) {
1142 case FGPositioned::VOR:
1143 case FGPositioned::LOC:
1144 case FGPositioned::TACAN: {
1145 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1146 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1148 if (pos == _nav1Station) {
1149 heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1150 } else if (pos == _nav2Station) {
1151 heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1154 nd->setIntValue("heading-deg", heading);
1158 case FGPositioned::AIRPORT:
1159 case FGPositioned::SEAPORT:
1160 case FGPositioned::HELIPORT:
1164 case FGPositioned::RUNWAY: {
1165 FGRunway* rwy = static_cast<FGRunway*>(pos);
1166 heading = rwy->headingDeg();
1167 nd->setDoubleValue("heading-deg", heading);
1168 nd->setIntValue("length-ft", rwy->lengthFt());
1169 nd->setStringValue("airport", rwy->airport()->ident());
1178 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1180 if (_routeSources.count(pos) != 0) {
1181 states.insert("on-active-route");
1184 switch (pos->type()) {
1185 case FGPositioned::VOR:
1186 case FGPositioned::LOC:
1187 if (pos == _nav1Station) {
1188 states.insert("tuned");
1189 states.insert("nav1");
1192 if (pos == _nav2Station) {
1193 states.insert("tuned");
1194 states.insert("nav2");
1198 case FGPositioned::AIRPORT:
1199 case FGPositioned::SEAPORT:
1200 case FGPositioned::HELIPORT:
1202 // once the FMS system has some way to tell us about them, of course
1204 if (pos == _route->departureAirport()) {
1205 states.insert("departure");
1208 if (pos == _route->destinationAirport()) {
1209 states.insert("destination");
1213 case FGPositioned::RUNWAY:
1214 if (pos == _route->departureRunway()) {
1215 states.insert("departure");
1218 if (pos == _route->destinationRunway()) {
1219 states.insert("destination");
1223 case FGPositioned::OBSTACLE:
1225 FGObstacle* obs = (FGObstacle*) pos;
1227 states.insert("lit");
1230 if (obj->getHeightAGLFt() >= 1000) {
1231 states.insert("greater-1000-ft");
1238 } // FGPositioned::Type switch
1241 static string mapAINodeToType(SGPropertyNode* model)
1243 // assume all multiplayer items are aircraft for the moment. Not ideal.
1244 if (!strcmp(model->getName(), "multiplayer")) {
1245 return "ai-aircraft";
1248 return string("ai-") + model->getName();
1251 void NavDisplay::processAI()
1253 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1254 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1255 SGPropertyNode *model = ai->getChild(i);
1256 if (!model->nChildren()) {
1260 // prefix types with 'ai-', to avoid any chance of namespace collisions
1261 // with fg-positioned.
1263 computeAIStates(model, ss);
1264 SymbolRuleVector rules;
1265 findRules(mapAINodeToType(model), ss, rules);
1266 if (rules.empty()) {
1267 return; // no rules matched, we can skip this item
1270 double heading = model->getDoubleValue("orientation/true-heading-deg");
1271 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1272 model->getDoubleValue("position/latitude-deg"),
1273 model->getDoubleValue("position/altitude-ft"));
1274 // compute some additional props
1275 int fl = (aiModelPos.getElevationFt() / 1000);
1276 model->setIntValue("flight-level", fl * 10);
1278 osg::Vec2 projected = projectGeod(aiModelPos);
1279 BOOST_FOREACH(SymbolRule* r, rules) {
1280 addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1282 } // of ai models iteration
1285 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1287 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1288 if (threatLevel < 1)
1291 states.insert("tcas");
1293 std::ostringstream os;
1294 os << "tcas-threat-level-" << threatLevel;
1295 states.insert(os.str());
1297 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1298 if (vspeed < -3.0) {
1299 states.insert("descending");
1300 } else if (vspeed > 3.0) {
1301 states.insert("climbing");
1305 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1307 if (isProjectedClipped(proj)) {
1311 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1312 _symbols.push_back(sym);
1316 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1318 double size = _odg->size();
1319 return (projected.x() < 0.0) ||
1320 (projected.y() < 0.0) ||
1321 (projected.x() >= size) ||
1322 (projected.y() >= size);
1325 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1327 string_set stateSet;
1328 BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1332 SymbolRuleVector rules;
1333 findRules(type, stateSet, rules);
1334 if (rules.empty()) {
1335 return; // no rules matched, we can skip this item
1338 osg::Vec2 projected = projectGeod(pos);
1339 BOOST_FOREACH(SymbolRule* r, rules) {
1340 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1344 void NavDisplay::addTestSymbols()
1346 _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1350 SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1352 addTestSymbol("airport", "", a1, 0.0, NULL);
1354 SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1356 addTestSymbol("vor", "", a1, 0.0, NULL);
1358 SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1360 addTestSymbol("airport", "destination", a1, 0.0, NULL);
1362 SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1363 addTestSymbol("fix", "", a1, 0.0, NULL);
1366 SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1367 addTestSymbol("fix", "", a1, 0.0, NULL);
1369 SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);
1370 addTestSymbol("fix", "", a1, 0.0, NULL);
1372 SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);
1373 addTestSymbol("fix", "", a1, 0.0, NULL);
1376 void NavDisplay::addRule(SymbolRule* r)
1378 _rules.push_back(r);