]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/NavDisplay.cxx
NavDisplay - cache nearby positioned items, and fix symbol instance queue to be clear...
[flightgear.git] / src / Instrumentation / NavDisplay.cxx
1 // navigation display texture
2 //
3 // Written by James Turner, forked from wxradar code
4 //
5 //
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.
10 //
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.
15 //
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.
19 //
20 //
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include "NavDisplay.hxx"
27
28 #include <cassert>
29 #include <boost/foreach.hpp>
30 #include <algorithm>
31
32 #include <osg/Array>
33 #include <osg/Geometry>
34 #include <osg/Matrixf>
35 #include <osg/PrimitiveSet>
36 #include <osg/StateSet>
37 #include <osg/LineWidth>
38 #include <osg/Version>
39
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>
46
47 #include <sstream>
48 #include <iomanip>
49 #include <iostream>             // for cout, endl
50
51 using std::stringstream;
52 using std::endl;
53 using std::setprecision;
54 using std::fixed;
55 using std::setw;
56 using std::setfill;
57 using std::cout;
58 using std::endl;
59
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>
70
71 #include "instrument_mgr.hxx"
72 #include "od_gauge.hxx"
73
74 static const char *DEFAULT_FONT = "typewriter.txf";
75
76 static
77 osg::Matrixf degRotation(float angle)
78 {
79     return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
80 }
81
82 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
83 {
84     osg::Vec4 result;
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());
89     return result;
90 }
91
92 static osgText::Text::AlignmentType readAlignment(const std::string& t)
93 {
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;
118     }
119     
120     return osgText::Text::BASE_LINE;
121 }
122
123 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
124 {
125     assert(nd);
126     static char buf[512];
127     if (format.find('d') != string::npos) {
128         ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
129         return buf;
130     }
131     
132     if (format.find('s') != string::npos) {
133         ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
134         return buf;
135     }
136     
137 // assume it's a double/float
138     ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
139     return buf;
140 }
141
142 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
143 {
144     osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
145     return osg::Vec2(r.x(), r.y());
146 }
147
148 class NavDisplay::CacheListener : public SGPropertyChangeListener
149 {
150 public:
151     CacheListener(NavDisplay *nd) : 
152         _nd(nd)
153     {}
154     
155     virtual void valueChanged (SGPropertyNode * prop)
156     {
157         _nd->invalidatePositionedCache();
158         SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache");
159     }
160 private:
161     NavDisplay* _nd;
162 };
163
164 ///////////////////////////////////////////////////////////////////
165
166 class SymbolDef
167 {
168 public:
169   SymbolDef() :
170       enable(NULL)
171     {}
172   
173     bool initFromNode(SGPropertyNode* node)
174     {
175         type = node->getStringValue("type");
176         SGPropertyNode* enableNode = node->getChild("enable");
177         if (enableNode) { 
178             enable = sgReadCondition(fgGetNode("/"), enableNode);
179         }
180       
181         int n=0;
182         while (node->hasChild("state", n)) {
183             string m = node->getChild("state", n++)->getStringValue();
184             if (m[0] == '!') {
185                 excluded_states.insert(m.substr(1));
186             } else {
187                 required_states.insert(m);
188             }
189         } // of matches parsing
190         
191       if (node->hasChild("width")) {
192         float w = node->getFloatValue("width");
193         float h = node->getFloatValue("height", w);
194         xy0.x() = -w * 0.5;
195         xy0.y() = -h * 0.5;
196         xy1.x() = w * 0.5;
197         xy1.y() = h * 0.5;
198       } else {
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);
203       }
204       
205         double texSize = node->getFloatValue("texture-size", 1.0);
206         
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;
211         
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);
217         hasText = false;
218         if (node->hasChild("text")) {
219             hasText = true;
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);
225         }
226         
227         drawLine = node->getBoolValue("draw-line", false);
228         lineColor = readColor(node->getChild("line-color"), color);
229         drawRouteLeg = node->getBoolValue("draw-leg", false);
230         
231         stretchSymbol = node->getBoolValue("stretch-symbol", false);
232         if (stretchSymbol) {
233             stretchY2 = node->getFloatValue("y2");
234             stretchY3 = node->getFloatValue("y3");
235             stretchV2 = node->getFloatValue("v2");
236             stretchV3 = node->getFloatValue("v3");
237         }
238       
239         return true;
240     }
241     
242     SGCondition* enable;
243     bool enabled; // cached enabled state
244     
245     std::string type;
246     string_set required_states;
247     string_set excluded_states;
248     
249     osg::Vec2 xy0, xy1;
250     osg::Vec2 uv0, uv1;
251     osg::Vec4 color;
252     
253     int priority;
254     int zOrder;
255     bool rotateToHeading;
256     bool roundPos; ///< should position be rounded to integer values
257     bool hasText;
258     osg::Vec4 textColor;
259     osg::Vec2 textOffset;
260     osgText::Text::AlignmentType alignment;
261     string textTemplate;
262     
263     bool drawLine;
264     osg::Vec4 lineColor;
265     
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.
270     bool stretchSymbol;
271     double stretchY2, stretchY3;
272     double stretchV2, stretchV3;
273     
274     bool drawRouteLeg;
275     
276     bool matches(const string_set& states) const
277     {
278         BOOST_FOREACH(const string& s, required_states) {
279             if (states.count(s) == 0) {
280                 return false;
281             }
282         }
283         
284         BOOST_FOREACH(const string& s, excluded_states) {
285             if (states.count(s) != 0) {
286                 return false;
287             }
288         }
289         
290         return true;
291     }
292 };
293
294 class SymbolInstance
295 {
296 public:
297     SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
298         pos(p),
299         headingDeg(h),
300         definition(def),
301         props(vars)
302     { }
303     
304     osg::Vec2 pos; // projected position
305     osg::Vec2 endPos;
306     double headingDeg;
307     SymbolDef* definition;
308     SGPropertyNode_ptr props;
309     
310     string text() const
311     {
312         assert(definition->hasText);
313         string r;        
314         size_t lastPos = 0;
315         
316         while (true) {
317             size_t pos = definition->textTemplate.find('{', lastPos);
318             if (pos == string::npos) { // no more replacements
319                 r.append(definition->textTemplate.substr(lastPos));
320                 break;
321             }
322             
323             r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
324             
325             size_t endReplacement = definition->textTemplate.find('}', pos+1);
326             if (endReplacement <= pos) {
327                 return "bad replacement";
328             }
329
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));
336             } else {
337                 string format = spec.substr(colonPos + 1);
338                 string prop = spec.substr(0, colonPos);
339                 r.append(formatPropertyValue(props->getNode(prop), format));
340             }
341             
342             lastPos = endReplacement + 1;
343         }
344         
345         return r;
346     }
347 };
348
349 //////////////////////////////////////////////////////////////////
350
351 NavDisplay::NavDisplay(SGPropertyNode *node) :
352     _name(node->getStringValue("name", "nd")),
353     _num(node->getIntValue("number", 0)),
354     _time(0.0),
355     _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
356     _odg(0),
357     _scale(0),
358     _view_heading(0),
359     _resultTexture(0),
360     _font_size(0),
361     _font_spacing(0),
362     _rangeNm(0)
363 {
364     _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
365     _font_node = _Instrument->getNode("font", true);
366
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);
375 #undef INITFONT
376
377     SGPropertyNode* symbolsNode = node->getNode("symbols");
378     SGPropertyNode* symbol;
379   
380     for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
381         SymbolDef* def = new SymbolDef;
382         if (!def->initFromNode(symbol)) {
383           delete def;
384           continue;
385         }
386         
387         _rules.push_back(def);
388     } // of symbol definition parsing
389 }
390
391
392 NavDisplay::~NavDisplay()
393 {
394 }
395
396
397 void
398 NavDisplay::init ()
399 {
400     _cachedItemsValid = false;
401     _cacheListener.reset(new CacheListener(this));
402     
403     _serviceable_node = _Instrument->getNode("serviceable", true);
404     _rangeNode = _Instrument->getNode("range", true);
405     _rangeNode->setDoubleValue(40.0);
406     _rangeNode->addChangeListener(_cacheListener.get());
407     
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);
412
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);
418     }
419   
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);
422
423     FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
424     _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
425     _odg->setSize(_Instrument->getIntValue("texture-size", 512));
426
427     _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
428     
429     _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
430     _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
431     
432     _excessDataNode = _Instrument->getChild("excess-data", 0, true);
433     _excessDataNode->setBoolValue(false);
434   
435 // OSG geometry setup
436     _radarGeode = new osg::Geode;
437
438     _geom = new osg::Geometry;
439     _geom->setUseDisplayList(false);
440     
441     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
442     stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
443     
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);
453     
454     _quadColors = new osg::Vec4Array;
455     _quadColors->setDataVariance(osg::Object::DYNAMIC);
456     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
457     _geom->setColorArray(_quadColors);
458     
459     _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
460     _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
461     _geom->addPrimitiveSet(_symbolPrimSet);
462     
463     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
464         osg::Vec3f(256.0f, 256.0f, 0.0f)));
465   
466     _radarGeode->addDrawable(_geom);
467     _odg->allocRT();
468     // Texture in the 2D panel system
469     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
470
471     _lineGeometry = new osg::Geometry;
472     _lineGeometry->setUseDisplayList(false);
473     stateSet = _lineGeometry->getOrCreateStateSet();    
474     osg::LineWidth *lw = new osg::LineWidth();
475     lw->setWidth(2.0);
476     stateSet->setAttribute(lw);
477     
478     _lineVertices = new osg::Vec2Array;
479     _lineVertices->setDataVariance(osg::Object::DYNAMIC);
480     _lineVertices->reserve(128 * 4);
481     _lineGeometry->setVertexArray(_lineVertices);
482     
483                   
484     _lineColors = new osg::Vec4Array;
485     _lineColors->setDataVariance(osg::Object::DYNAMIC);
486     _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
487     _lineGeometry->setColorArray(_lineColors);
488     
489     _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
490     _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
491     _lineGeometry->addPrimitiveSet(_linePrimSet);
492     
493     _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
494                                             osg::Vec3f(256.0f, 256.0f, 0.0f)));
495
496     _radarGeode->addDrawable(_lineGeometry);              
497                   
498     _textGeode = new osg::Geode;
499
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());
506     
507     updateFont();
508 }
509
510 void
511 NavDisplay::update (double delta_time_sec)
512 {
513   if (!fgGetBool("sim/sceneryloaded", false)) {
514     return;
515   }
516
517   if (!_odg || !_serviceable_node->getBoolValue()) {
518     _Instrument->setStringValue("status", "");
519     return;
520   }
521   
522   _time += delta_time_sec;
523   if (_time < _updateInterval){
524     return;
525   }
526   _time -= _updateInterval;
527
528   _rangeNm = _rangeNode->getFloatValue();
529   if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
530     _view_heading = fgGetDouble("/orientation/heading-deg");
531   } else {
532     _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
533   }
534   
535   _scale = _odg->size() / _rangeNm;
536   
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);
541
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;
546   
547   _pos = globals->get_aircraft_position();
548
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);
556         }
557     }
558     
559   _vertices->clear();
560   _lineVertices->clear();
561   _lineColors->clear();
562   _quadColors->clear();
563   _texCoords->clear();
564   _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
565   
566   BOOST_FOREACH(SymbolInstance* si, _symbols) {
567       delete si;
568   }
569   _symbols.clear();
570     
571   BOOST_FOREACH(SymbolDef* def, _rules) {
572     if (def->enable) {
573       def->enabled = def->enable->test();
574     } else {
575       def->enabled = true;
576     }
577   }
578   
579   processRoute();
580   processNavRadios();
581   processAI();
582   findItems();
583   limitDisplayedSymbols();
584   addSymbolsToScene();
585   
586   _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
587   _symbolPrimSet->dirty();
588   _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
589   _linePrimSet->dirty();
590 }
591
592
593 void
594 NavDisplay::updateFont()
595 {
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);
601
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);
605
606     SGPath tpath;
607     if (path[0] != '/') {
608         tpath = globals->get_fg_root();
609         tpath.append("Fonts");
610         tpath.append(path);
611     } else {
612         tpath = path;
613     }
614
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());
617
618     if (font != 0) {
619         _font = font;
620         _font->setMinFilterHint(osg::Texture::NEAREST);
621         _font->setMagFilterHint(osg::Texture::NEAREST);
622         _font->setGlyphImageMargin(0);
623         _font->setGlyphImageMarginRatio(0);
624     }
625 }
626
627 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
628 {
629     SymbolDef* def = sym->definition;
630     
631     osg::Vec2 verts[4];
632     verts[0] = def->xy0;
633     verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
634     verts[2] = def->xy1;
635     verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
636     
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);
641         }
642     }
643     
644     osg::Vec2 pos = sym->pos;
645     if (def->roundPos) {
646         pos = osg::Vec2((int) pos.x(), (int) pos.y());
647     }
648     
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()));
653
654     for (int i=0; i<4; ++i) {
655         _vertices->push_back(verts[i] + pos);
656         _quadColors->push_back(def->color);
657     }
658     
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);
665         
666         osg::Matrixf m(degRotation(sym->headingDeg));
667         for (int i=0; i<4; ++i) {
668             stretchVerts[i] = mult(stretchVerts[i], m);
669         }
670         
671     // stretched quad
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);
676         
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()));
681         
682         for (int i=0; i<4; ++i) {
683             _quadColors->push_back(def->color);
684         }
685         
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);
690         }
691         
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));
696     }
697     
698     if (def->drawLine) {
699         addLine(sym->pos, sym->endPos, def->lineColor);
700     }
701     
702     if (!def->hasText) {
703         return;
704     }
705     
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());
714
715
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);
720 }
721
722 class OrderByPriority
723 {
724 public:
725     bool operator()(SymbolInstance* a, SymbolInstance* b)
726     {
727         return a->definition->priority > b->definition->priority;
728     }    
729 };
730
731 void NavDisplay::limitDisplayedSymbols()
732 {
733     unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
734     if (_symbols.size() <= maxSymbols) {
735         _excessDataNode->setBoolValue(false);
736         return;
737     }
738     
739     std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
740     _symbols.resize(maxSymbols);
741     _excessDataNode->setBoolValue(true);
742 }
743
744 class OrderByZ
745 {
746 public:
747     bool operator()(SymbolInstance* a, SymbolInstance* b)
748     {
749         return a->definition->zOrder > b->definition->zOrder;
750     }
751 };
752
753 void NavDisplay::addSymbolsToScene()
754 {
755     std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
756     BOOST_FOREACH(SymbolInstance* sym, _symbols) {
757         addSymbolToScene(sym);
758     }
759 }
760
761 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
762 {    
763     _lineVertices->push_back(a);
764     _lineVertices->push_back(b);
765     _lineColors->push_back(color);
766     _lineColors->push_back(color);
767 }
768
769 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
770 {
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());
775 }
776
777 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
778 {
779     double rangeM, bearing, az2;
780     SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
781     return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
782 }
783
784 class Filter : public FGPositioned::Filter
785 {
786 public:
787     double minRunwayLengthFt;
788   
789     virtual bool pass(FGPositioned* aPos) const
790     {
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])) {
795                 return false;
796             }
797         }
798
799         if (aPos->type() == FGPositioned::AIRPORT) {
800           FGAirport* apt = (FGAirport*) aPos;
801           if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
802             return false;
803           }
804         }
805       
806         return true;
807     }
808
809     virtual FGPositioned::Type minType() const {
810         return FGPositioned::AIRPORT;
811     }
812
813     virtual FGPositioned::Type maxType() const {
814         return FGPositioned::OBSTACLE;
815     }
816 };
817
818 void NavDisplay::findItems()
819 {
820     if (!_cachedItemsValid) {
821         SG_LOG(SG_INSTR, SG_INFO, "re-validating NavDisplay cache");
822         Filter filt;
823         filt.minRunwayLengthFt = 2000;
824         _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
825         _cachedItemsValid = true;
826         _cachedPos = SGVec3d::fromGeod(_pos);
827     }
828     
829     BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
830         foundPositionedItem(pos);
831     }
832 }
833
834 void NavDisplay::processRoute()
835 {
836     _routeSources.clear();
837     RoutePath path(_route->waypts());
838     int current = _route->currentIndex();
839     
840     for (int w=0; w<_route->numWaypts(); ++w) {
841         flightgear::WayptRef wpt(_route->wayptAtIndex(w));
842         _routeSources.insert(wpt->source());
843         
844         string_set state;
845         state.insert("on-active-route");
846         
847         if (w < current) {
848             state.insert("passed");
849         }
850         
851         if (w == current) {
852             state.insert("current-wp");
853         }
854         
855         if (w > current) {
856             state.insert("future");
857         }
858         
859         if (w == (current + 1)) {
860             state.insert("next-wp");
861         }
862         
863         SymbolDefVector rules;
864         findRules("waypoint" , state, rules);
865         if (rules.empty()) {
866             return; // no rules matched, we can skip this item
867         }
868
869         SGGeod g = path.positionForIndex(w);
870         SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
871         double heading;
872         computeWayptPropsAndHeading(wpt, g, vars, heading);
873
874         osg::Vec2 projected = projectGeod(g);
875         BOOST_FOREACH(SymbolDef* r, rules) {
876             addSymbolInstance(projected, heading, r, vars);
877             
878             if (r->drawRouteLeg) {
879                 SGGeodVec gv(path.pathForIndex(w));
880                 if (!gv.empty()) {
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);
885                         pr = p;
886                     }
887                 }
888             } // of leg drawing enabled
889         } // of matching rules iteration
890     } // of waypoints iteration
891 }
892
893 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
894 {
895     double rangeM, az2;
896     SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
897     nd->setIntValue("radial", heading);
898     nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
899     
900     heading = nd->getDoubleValue("leg-bearing-true-deg");
901 }
902
903 void NavDisplay::processNavRadios()
904 {
905     _nav1Station = processNavRadio(_navRadio1Node);
906     _nav2Station = processNavRadio(_navRadio2Node);
907     
908     foundPositionedItem(_nav1Station);
909     foundPositionedItem(_nav2Station);
910 }
911
912 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
913 {
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
918         return NULL;
919     }
920     
921     
922     return nav;
923 }
924
925 bool NavDisplay::anyRuleForType(const string& type) const
926 {
927     BOOST_FOREACH(SymbolDef* r, _rules) {
928         if (!r->enabled) {
929             continue;
930         }
931     
932         if (r->type == type) {
933             return true;
934         }
935     }
936     
937     return false;
938 }
939
940 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
941 {
942     BOOST_FOREACH(SymbolDef* r, _rules) {
943         if (!r->enabled || (r->type != type)) {
944             continue;
945         }
946
947         if (r->matches(states)) {
948             return true;
949         }
950     } // of rules iteration
951     
952     return false;
953 }
954
955 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
956 {
957     BOOST_FOREACH(SymbolDef* candidate, _rules) {
958         if (!candidate->enabled || (candidate->type != type)) {
959             continue;
960         }
961         
962         if (candidate->matches(states)) {
963             rules.push_back(candidate);
964         }
965     }
966 }
967
968 void NavDisplay::foundPositionedItem(FGPositioned* pos)
969 {
970     if (!pos) {
971         return;
972     }
973     
974     string type = FGPositioned::nameForType(pos->type());
975     if (!anyRuleForType(type)) {
976         return; // not diplayed at all, we're done
977     }
978     
979     string_set states;
980     computePositionedState(pos, states);
981     
982     SymbolDefVector rules;
983     findRules(type, states, rules);
984     if (rules.empty()) {
985         return; // no rules matched, we can skip this item
986     }
987     
988     SGPropertyNode_ptr vars(new SGPropertyNode);
989     double heading;
990     computePositionedPropsAndHeading(pos, vars, heading);
991     
992     osg::Vec2 projected = projectGeod(pos->geod());
993     BOOST_FOREACH(SymbolDef* r, rules) {
994         addSymbolInstance(projected, heading, r, vars);
995     }
996 }
997
998 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
999 {
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);
1004     
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());
1011         
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"));
1016         }
1017         
1018         break;
1019     }
1020
1021     case FGPositioned::AIRPORT:
1022     case FGPositioned::SEAPORT:
1023     case FGPositioned::HELIPORT:
1024         
1025         break;
1026         
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());
1032         break;
1033     }
1034
1035     default:
1036         break; 
1037     }
1038 }
1039
1040 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1041 {
1042     if (_routeSources.count(pos) != 0) {
1043         states.insert("on-active-route");
1044     }
1045     
1046     switch (pos->type()) {
1047     case FGPositioned::VOR:
1048     case FGPositioned::LOC:
1049         if (pos == _nav1Station) {
1050             states.insert("tuned");
1051             states.insert("nav1");
1052         }
1053         
1054         if (pos == _nav2Station) {
1055             states.insert("tuned");
1056             states.insert("nav2");
1057         }
1058         break;
1059     
1060     case FGPositioned::AIRPORT:
1061     case FGPositioned::SEAPORT:
1062     case FGPositioned::HELIPORT:
1063         // mark alternates!
1064         // once the FMS system has some way to tell us about them, of course
1065         
1066         if (pos == _route->departureAirport()) {
1067             states.insert("departure");
1068         }
1069         
1070         if (pos == _route->destinationAirport()) {
1071             states.insert("destination");
1072         }
1073         break;
1074     
1075     case FGPositioned::RUNWAY:
1076         if (pos == _route->departureRunway()) {
1077             states.insert("departure");
1078         }
1079         
1080         if (pos == _route->destinationRunway()) {
1081             states.insert("destination");
1082         }
1083         break;
1084     
1085     case FGPositioned::OBSTACLE:
1086     #if 0    
1087         FGObstacle* obs = (FGObstacle*) pos;
1088         if (obj->isLit()) {
1089             states.insert("lit");
1090         }
1091         
1092         if (obj->getHeightAGLFt() >= 1000) {
1093             states.insert("greater-1000-ft");
1094         }
1095     #endif
1096         break;
1097     
1098     default:
1099         break;
1100     } // FGPositioned::Type switch
1101 }
1102
1103 void NavDisplay::processAI()
1104 {
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()) {
1109             continue;
1110         }
1111         
1112     // prefix types with 'ai-', to avoid any chance of namespace collisions
1113     // with fg-positioned.
1114         string_set ss;
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
1120         }
1121
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);
1129                                             
1130         osg::Vec2 projected = projectGeod(aiModelPos);
1131         BOOST_FOREACH(SymbolDef* r, rules) {
1132             addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1133         }
1134     } // of ai models iteration
1135 }
1136
1137 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1138 {
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));
1143     }
1144     
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");
1150     }
1151 }
1152
1153 bool NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1154 {
1155     if (isProjectedClipped(proj)) {
1156         return false;
1157     }
1158     
1159     SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1160     _symbols.push_back(sym);
1161     return true;
1162 }
1163
1164 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1165 {
1166     double size = _odg->size();
1167     return (projected.x() < 0.0) ||
1168         (projected.y() < 0.0) ||
1169         (projected.x() >= size) ||
1170             (projected.y() >= size);
1171 }
1172
1173
1174
1175