]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/NavDisplay.cxx
Nav-display: expose TCAS threat level correctly.
[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/misc/strutils.hxx>
46 #include <simgear/math/sg_geodesy.hxx>
47
48 #include <sstream>
49 #include <iomanip>
50 #include <iostream>             // for cout, endl
51
52 using std::stringstream;
53 using std::endl;
54 using std::setprecision;
55 using std::fixed;
56 using std::setw;
57 using std::setfill;
58 using std::cout;
59 using std::endl;
60
61 #include <Main/fg_props.hxx>
62 #include <Main/globals.hxx>
63 #include <Cockpit/panel.hxx>
64 #include <Navaids/routePath.hxx>
65 #include <Autopilot/route_mgr.hxx>
66 #include <Navaids/navrecord.hxx>
67 #include <Navaids/navlist.hxx>
68 #include <Navaids/fix.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/runways.hxx>
71
72 #include "instrument_mgr.hxx"
73 #include "od_gauge.hxx"
74
75 static const char *DEFAULT_FONT = "typewriter.txf";
76
77 static
78 osg::Matrixf degRotation(float angle)
79 {
80     return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
81 }
82
83 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
84 {
85     osg::Vec4 result;
86     result.r() = colorNode->getDoubleValue("red",   c.r());
87     result.g() = colorNode->getDoubleValue("green", c.g());
88     result.b() = colorNode->getDoubleValue("blue",  c.b());
89     result.a() = colorNode->getDoubleValue("alpha", c.a());
90     return result;
91 }
92
93 static osgText::Text::AlignmentType readAlignment(const std::string& t)
94 {
95     if (t == "left-top") {
96         return osgText::Text::LEFT_TOP;
97     } else if (t == "left-center") {
98         return osgText::Text::LEFT_CENTER;
99     } else if (t == "left-bottom") {
100         return osgText::Text::LEFT_BOTTOM;
101     } else if (t == "center-top") {
102         return osgText::Text::CENTER_TOP;
103     } else if (t == "center-center") {
104         return osgText::Text::CENTER_CENTER;
105     } else if (t == "center-bottom") {
106         return osgText::Text::CENTER_BOTTOM;
107     } else if (t == "right-top") {
108         return osgText::Text::RIGHT_TOP;
109     } else if (t == "right-center") {
110         return osgText::Text::RIGHT_CENTER;
111     } else if (t == "right-bottom") {
112         return osgText::Text::RIGHT_BOTTOM;
113     } else if (t == "left-baseline") {
114         return osgText::Text::LEFT_BASE_LINE;
115     } else if (t == "center-baseline") {
116         return osgText::Text::CENTER_BASE_LINE;
117     } else if (t == "right-baseline") {
118         return osgText::Text::RIGHT_BASE_LINE;
119     }
120     
121     return osgText::Text::BASE_LINE;
122 }
123
124 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
125 {
126     assert(nd);
127     static char buf[512];
128     if (format.find('d') != string::npos) {
129         ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
130         return buf;
131     }
132     
133     if (format.find('s') != string::npos) {
134         ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
135         return buf;
136     }
137     
138 // assume it's a double/float
139     ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
140     return buf;
141 }
142
143 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
144 {
145     osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
146     return osg::Vec2(r.x(), r.y());
147 }
148
149 class NavDisplay::CacheListener : public SGPropertyChangeListener
150 {
151 public:
152     CacheListener(NavDisplay *nd) : 
153         _nd(nd)
154     {}
155     
156     virtual void valueChanged (SGPropertyNode * prop)
157     {
158         _nd->invalidatePositionedCache();
159         SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache");
160     }
161 private:
162     NavDisplay* _nd;
163 };
164
165 ///////////////////////////////////////////////////////////////////
166
167 class SymbolDef
168 {
169 public:
170   SymbolDef() :
171       enable(NULL)
172     {}
173   
174     bool initFromNode(SGPropertyNode* node)
175     {
176         type = node->getStringValue("type");
177         SGPropertyNode* enableNode = node->getChild("enable");
178         if (enableNode) { 
179             enable = sgReadCondition(fgGetNode("/"), enableNode);
180         }
181       
182         int n=0;
183         while (node->hasChild("state", n)) {
184             string m = node->getChild("state", n++)->getStringValue();
185             if (m[0] == '!') {
186                 excluded_states.insert(m.substr(1));
187             } else {
188                 required_states.insert(m);
189             }
190         } // of matches parsing
191         
192       if (node->hasChild("width")) {
193         float w = node->getFloatValue("width");
194         float h = node->getFloatValue("height", w);
195         xy0.x() = -w * 0.5;
196         xy0.y() = -h * 0.5;
197         xy1.x() = w * 0.5;
198         xy1.y() = h * 0.5;
199       } else {
200         xy0.x()  = node->getFloatValue("x0", 0.0);
201         xy0.y()  = node->getFloatValue("y0", 0.0);
202         xy1.x()  = node->getFloatValue("x1", 5);
203         xy1.y()  = node->getFloatValue("y1", 5);
204       }
205       
206         double texSize = node->getFloatValue("texture-size", 1.0);
207         
208         uv0.x()  = node->getFloatValue("u0", 0) / texSize;
209         uv0.y()  = node->getFloatValue("v0", 0) / texSize;
210         uv1.x()  = node->getFloatValue("u1", 1) / texSize;
211         uv1.y()  = node->getFloatValue("v1", 1) / texSize;
212         
213         color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
214         priority = node->getIntValue("priority", 0);
215         zOrder = node->getIntValue("zOrder", 0);
216         rotateToHeading = node->getBoolValue("rotate-to-heading", false);
217         roundPos = node->getBoolValue("round-position", true);
218         hasText = false;
219         if (node->hasChild("text")) {
220             hasText = true;
221             alignment = readAlignment(node->getStringValue("text-align"));
222             textTemplate = node->getStringValue("text");
223             textOffset.x() = node->getFloatValue("text-offset-x", 0);
224             textOffset.y() = node->getFloatValue("text-offset-y", 0);
225             textColor = readColor(node->getChild("text-color"), color);
226         }
227         
228         drawLine = node->getBoolValue("draw-line", false);
229         lineColor = readColor(node->getChild("line-color"), color);
230         drawRouteLeg = node->getBoolValue("draw-leg", false);
231         
232         stretchSymbol = node->getBoolValue("stretch-symbol", false);
233         if (stretchSymbol) {
234             stretchY2 = node->getFloatValue("y2");
235             stretchY3 = node->getFloatValue("y3");
236             stretchV2 = node->getFloatValue("v2");
237             stretchV3 = node->getFloatValue("v3");
238         }
239       
240         return true;
241     }
242     
243     SGCondition* enable;
244     bool enabled; // cached enabled state
245     
246     std::string type;
247     string_set required_states;
248     string_set excluded_states;
249     
250     osg::Vec2 xy0, xy1;
251     osg::Vec2 uv0, uv1;
252     osg::Vec4 color;
253     
254     int priority;
255     int zOrder;
256     bool rotateToHeading;
257     bool roundPos; ///< should position be rounded to integer values
258     bool hasText;
259     osg::Vec4 textColor;
260     osg::Vec2 textOffset;
261     osgText::Text::AlignmentType alignment;
262     string textTemplate;
263     
264     bool drawLine;
265     osg::Vec4 lineColor;
266     
267 // symbol stretching creates three quads (instead of one) - a start,
268 // middle and end quad, positioned along the line of the symbol.
269 // X (and U) axis values determined by the values above, so we only need
270 // to define the Y (and V) values to build the other quads.
271     bool stretchSymbol;
272     double stretchY2, stretchY3;
273     double stretchV2, stretchV3;
274     
275     bool drawRouteLeg;
276     
277     bool matches(const string_set& states) const
278     {
279         BOOST_FOREACH(const string& s, required_states) {
280             if (states.count(s) == 0) {
281                 return false;
282             }
283         }
284         
285         BOOST_FOREACH(const string& s, excluded_states) {
286             if (states.count(s) != 0) {
287                 return false;
288             }
289         }
290         
291         return true;
292     }
293 };
294
295 class SymbolInstance
296 {
297 public:
298     SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
299         pos(p),
300         headingDeg(h),
301         definition(def),
302         props(vars)
303     { }
304     
305     osg::Vec2 pos; // projected position
306     osg::Vec2 endPos;
307     double headingDeg;
308     SymbolDef* definition;
309     SGPropertyNode_ptr props;
310     
311     string text() const
312     {
313         assert(definition->hasText);
314         string r;        
315         size_t lastPos = 0;
316         
317         while (true) {
318             size_t pos = definition->textTemplate.find('{', lastPos);
319             if (pos == string::npos) { // no more replacements
320                 r.append(definition->textTemplate.substr(lastPos));
321                 break;
322             }
323             
324             r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
325             
326             size_t endReplacement = definition->textTemplate.find('}', pos+1);
327             if (endReplacement <= pos) {
328                 return "bad replacement";
329             }
330
331             string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
332         // look for formatter in spec
333             size_t colonPos = spec.find(':');
334             if (colonPos == string::npos) {
335             // simple replacement
336                 r.append(props->getStringValue(spec));
337             } else {
338                 string format = spec.substr(colonPos + 1);
339                 string prop = spec.substr(0, colonPos);
340                 r.append(formatPropertyValue(props->getNode(prop), format));
341             }
342             
343             lastPos = endReplacement + 1;
344         }
345         
346         return r;
347     }
348 };
349
350 //////////////////////////////////////////////////////////////////
351
352 NavDisplay::NavDisplay(SGPropertyNode *node) :
353     _name(node->getStringValue("name", "nd")),
354     _num(node->getIntValue("number", 0)),
355     _time(0.0),
356     _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
357     _odg(0),
358     _scale(0),
359     _view_heading(0),
360     _resultTexture(0),
361     _font_size(0),
362     _font_spacing(0),
363     _rangeNm(0)
364 {
365     _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
366     _font_node = _Instrument->getNode("font", true);
367
368 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
369     INITFONT("name", DEFAULT_FONT, String);
370     INITFONT("size", 8, Float);
371     INITFONT("line-spacing", 0.25, Float);
372     INITFONT("color/red", 0, Float);
373     INITFONT("color/green", 0.8, Float);
374     INITFONT("color/blue", 0, Float);
375     INITFONT("color/alpha", 1, Float);
376 #undef INITFONT
377
378     SGPropertyNode* symbolsNode = node->getNode("symbols");
379     SGPropertyNode* symbol;
380   
381     for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
382         SymbolDef* def = new SymbolDef;
383         if (!def->initFromNode(symbol)) {
384           delete def;
385           continue;
386         }
387         
388         _rules.push_back(def);
389     } // of symbol definition parsing
390 }
391
392
393 NavDisplay::~NavDisplay()
394 {
395 }
396
397
398 void
399 NavDisplay::init ()
400 {
401     _cachedItemsValid = false;
402     _cacheListener.reset(new CacheListener(this));
403     
404     _serviceable_node = _Instrument->getNode("serviceable", true);
405     _rangeNode = _Instrument->getNode("range", true);
406     _rangeNode->setDoubleValue(40.0);
407     _rangeNode->addChangeListener(_cacheListener.get());
408     
409     // texture name to use in 2D and 3D instruments
410     _texture_path = _Instrument->getStringValue("radar-texture-path",
411         "Aircraft/Instruments/Textures/od_wxradar.rgb");
412     _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
413
414     string path = _Instrument->getStringValue("symbol-texture-path",
415         "Aircraft/Instruments/Textures/nd-symbols.png");
416     SGPath tpath = globals->resolve_aircraft_path(path);
417     if (!tpath.exists()) {
418       SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
419     }
420   
421     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
422     _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
423
424     FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
425     _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
426     _odg->setSize(_Instrument->getIntValue("texture-size", 512));
427
428     _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
429     
430     _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
431     _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
432     
433     _excessDataNode = _Instrument->getChild("excess-data", 0, true);
434     _excessDataNode->setBoolValue(false);
435     _testModeNode = _Instrument->getChild("test-mode", 0, true);
436     _testModeNode->setBoolValue(false);
437   
438 // OSG geometry setup
439     _radarGeode = new osg::Geode;
440
441     _geom = new osg::Geometry;
442     _geom->setUseDisplayList(false);
443     
444     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
445     stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
446     
447     // Initially allocate space for 128 quads
448     _vertices = new osg::Vec2Array;
449     _vertices->setDataVariance(osg::Object::DYNAMIC);
450     _vertices->reserve(128 * 4);
451     _geom->setVertexArray(_vertices);
452     _texCoords = new osg::Vec2Array;
453     _texCoords->setDataVariance(osg::Object::DYNAMIC);
454     _texCoords->reserve(128 * 4);
455     _geom->setTexCoordArray(0, _texCoords);
456     
457     _quadColors = new osg::Vec4Array;
458     _quadColors->setDataVariance(osg::Object::DYNAMIC);
459     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
460     _geom->setColorArray(_quadColors);
461     
462     _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
463     _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
464     _geom->addPrimitiveSet(_symbolPrimSet);
465     
466     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
467         osg::Vec3f(256.0f, 256.0f, 0.0f)));
468   
469     _radarGeode->addDrawable(_geom);
470     _odg->allocRT();
471     // Texture in the 2D panel system
472     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
473
474     _lineGeometry = new osg::Geometry;
475     _lineGeometry->setUseDisplayList(false);
476     stateSet = _lineGeometry->getOrCreateStateSet();    
477     osg::LineWidth *lw = new osg::LineWidth();
478     lw->setWidth(2.0);
479     stateSet->setAttribute(lw);
480     
481     _lineVertices = new osg::Vec2Array;
482     _lineVertices->setDataVariance(osg::Object::DYNAMIC);
483     _lineVertices->reserve(128 * 4);
484     _lineGeometry->setVertexArray(_lineVertices);
485     
486                   
487     _lineColors = new osg::Vec4Array;
488     _lineColors->setDataVariance(osg::Object::DYNAMIC);
489     _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
490     _lineGeometry->setColorArray(_lineColors);
491     
492     _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
493     _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
494     _lineGeometry->addPrimitiveSet(_linePrimSet);
495     
496     _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
497                                             osg::Vec3f(256.0f, 256.0f, 0.0f)));
498
499     _radarGeode->addDrawable(_lineGeometry);              
500                   
501     _textGeode = new osg::Geode;
502
503     osg::Camera *camera = _odg->getCamera();
504     camera->addChild(_radarGeode.get());
505     camera->addChild(_textGeode.get());
506     osg::Texture2D* tex = _odg->getTexture();
507     camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(), 
508         0, tex->getTextureHeight());
509     
510     updateFont();
511 }
512
513 void
514 NavDisplay::update (double delta_time_sec)
515 {
516   if (!fgGetBool("sim/sceneryloaded", false)) {
517     return;
518   }
519
520   if (!_odg || !_serviceable_node->getBoolValue()) {
521     _Instrument->setStringValue("status", "");
522     return;
523   }
524   
525   _time += delta_time_sec;
526   if (_time < _updateInterval){
527     return;
528   }
529   _time -= _updateInterval;
530
531   _rangeNm = _rangeNode->getFloatValue();
532   if (_testModeNode->getBoolValue()) {
533     _view_heading = 90;
534   } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
535     _view_heading = fgGetDouble("/orientation/heading-deg");
536   } else {
537     _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
538   }
539   
540   double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
541   double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
542   int pixelSize = _odg->size();
543   
544   int rangePixels = _Instrument->getIntValue("range-pixels", -1);
545   if (rangePixels < 0) {
546     // hacky - assume (as is very common) that x-frac doesn't vary, and
547     // y-frac is used to position the center at either the top or bottom of
548     // the pixel area. Measure from the center to the furthest edge (top or bottom)
549     rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
550   }
551   
552   _scale = rangePixels / _rangeNm;
553   _Instrument->setDoubleValue("scale", _scale);
554   
555   
556   _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize, 
557       yCenterFrac * pixelSize, 0.0);
558
559 // scale from nm to display units, rotate so aircraft heading is up
560 // (as opposed to north), and compensate for centering
561   _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) * 
562       degRotation(-_view_heading) * _centerTrans;
563   
564   _pos = globals->get_aircraft_position();
565
566     // invalidate the cache of positioned items, if we travelled more than 1nm
567     if (_cachedItemsValid) {
568         SGVec3d cartNow(SGVec3d::fromGeod(_pos));
569         double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
570         _cachedItemsValid = (movedNm < 1.0);
571         if (!_cachedItemsValid) {
572             SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache due to moving: " << movedNm);
573         }
574     }
575     
576   _vertices->clear();
577   _lineVertices->clear();
578   _lineColors->clear();
579   _quadColors->clear();
580   _texCoords->clear();
581   _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
582   
583   BOOST_FOREACH(SymbolInstance* si, _symbols) {
584       delete si;
585   }
586   _symbols.clear();
587     
588   BOOST_FOREACH(SymbolDef* def, _rules) {
589     if (def->enable) {
590       def->enabled = def->enable->test();
591     } else {
592       def->enabled = true;
593     }
594   }
595   
596   if (_testModeNode->getBoolValue()) {
597     addTestSymbols();
598   } else {
599     processRoute();
600     processNavRadios();
601     processAI();
602     findItems();
603     limitDisplayedSymbols();
604   }
605
606   addSymbolsToScene();
607   
608   _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
609   _symbolPrimSet->dirty();
610   _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
611   _linePrimSet->dirty();
612 }
613
614
615 void
616 NavDisplay::updateFont()
617 {
618     float red = _font_node->getFloatValue("color/red");
619     float green = _font_node->getFloatValue("color/green");
620     float blue = _font_node->getFloatValue("color/blue");
621     float alpha = _font_node->getFloatValue("color/alpha");
622     _font_color.set(red, green, blue, alpha);
623
624     _font_size = _font_node->getFloatValue("size");
625     _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
626     string path = _font_node->getStringValue("name", DEFAULT_FONT);
627
628     SGPath tpath;
629     if (path[0] != '/') {
630         tpath = globals->get_fg_root();
631         tpath.append("Fonts");
632         tpath.append(path);
633     } else {
634         tpath = path;
635     }
636
637     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
638     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
639
640     if (font != 0) {
641         _font = font;
642         _font->setMinFilterHint(osg::Texture::NEAREST);
643         _font->setMagFilterHint(osg::Texture::NEAREST);
644         _font->setGlyphImageMargin(0);
645         _font->setGlyphImageMarginRatio(0);
646     }
647 }
648
649 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
650 {
651     SymbolDef* def = sym->definition;
652     
653     osg::Vec2 verts[4];
654     verts[0] = def->xy0;
655     verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
656     verts[2] = def->xy1;
657     verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
658     
659     if (def->rotateToHeading) {
660         osg::Matrixf m(degRotation(sym->headingDeg));
661         for (int i=0; i<4; ++i) {
662             verts[i] = mult(verts[i], m);
663         }
664     }
665     
666     osg::Vec2 pos = sym->pos;
667     if (def->roundPos) {
668         pos = osg::Vec2((int) pos.x(), (int) pos.y());
669     }
670     
671     _texCoords->push_back(def->uv0);
672     _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
673     _texCoords->push_back(def->uv1);
674     _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
675
676     for (int i=0; i<4; ++i) {
677         _vertices->push_back(verts[i] + pos);
678         _quadColors->push_back(def->color);
679     }
680     
681     if (def->stretchSymbol) {
682         osg::Vec2 stretchVerts[4];
683         stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
684         stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
685         stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
686         stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
687         
688         osg::Matrixf m(degRotation(sym->headingDeg));
689         for (int i=0; i<4; ++i) {
690             stretchVerts[i] = mult(stretchVerts[i], m);
691         }
692         
693     // stretched quad
694         _vertices->push_back(verts[2] + pos);
695         _vertices->push_back(stretchVerts[1] + sym->endPos);
696         _vertices->push_back(stretchVerts[0] + sym->endPos);
697         _vertices->push_back(verts[3] + pos);
698         
699         _texCoords->push_back(def->uv1);
700         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
701         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
702         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
703         
704         for (int i=0; i<4; ++i) {
705             _quadColors->push_back(def->color);
706         }
707         
708     // quad three, for the end portion
709         for (int i=0; i<4; ++i) {
710             _vertices->push_back(stretchVerts[i] + sym->endPos);
711             _quadColors->push_back(def->color);
712         }
713         
714         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
715         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
716         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
717         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
718     }
719     
720     if (def->drawLine) {
721         addLine(sym->pos, sym->endPos, def->lineColor);
722     }
723     
724     if (!def->hasText) {
725         return;
726     }
727     
728     osgText::Text* t = new osgText::Text;
729     t->setFont(_font.get());
730     t->setFontResolution(12, 12);
731     t->setCharacterSize(_font_size);
732     t->setLineSpacing(_font_spacing);
733     t->setColor(def->textColor);
734     t->setAlignment(def->alignment);
735     t->setText(sym->text());
736
737
738     osg::Vec2 textPos = def->textOffset + pos;
739 // ensure we use ints here, or text visual quality goes bad
740     t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
741     _textGeode->addDrawable(t);
742 }
743
744 class OrderByPriority
745 {
746 public:
747     bool operator()(SymbolInstance* a, SymbolInstance* b)
748     {
749         return a->definition->priority > b->definition->priority;
750     }    
751 };
752
753 void NavDisplay::limitDisplayedSymbols()
754 {
755     unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
756     if (_symbols.size() <= maxSymbols) {
757         _excessDataNode->setBoolValue(false);
758         return;
759     }
760     
761     std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
762     _symbols.resize(maxSymbols);
763     _excessDataNode->setBoolValue(true);
764 }
765
766 class OrderByZ
767 {
768 public:
769     bool operator()(SymbolInstance* a, SymbolInstance* b)
770     {
771         return a->definition->zOrder > b->definition->zOrder;
772     }
773 };
774
775 void NavDisplay::addSymbolsToScene()
776 {
777     std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
778     BOOST_FOREACH(SymbolInstance* sym, _symbols) {
779         addSymbolToScene(sym);
780     }
781 }
782
783 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
784 {    
785     _lineVertices->push_back(a);
786     _lineVertices->push_back(b);
787     _lineColors->push_back(color);
788     _lineColors->push_back(color);
789 }
790
791 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
792 {
793     osg::Vec3 p(0, rangeNm, 0.0);
794     p = degRotation(bearingDeg).preMult(p);
795     p = _projectMat.preMult(p);
796     return osg::Vec2(p.x(), p.y());
797 }
798
799 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
800 {
801     double rangeM, bearing, az2;
802     SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
803     return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
804 }
805
806 class Filter : public FGPositioned::Filter
807 {
808 public:
809     double minRunwayLengthFt;
810   
811     virtual bool pass(FGPositioned* aPos) const
812     {
813         if (aPos->type() == FGPositioned::FIX) {
814             string ident(aPos->ident());
815             // ignore fixes which end in digits
816             if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
817                 return false;
818             }
819         }
820
821         if (aPos->type() == FGPositioned::AIRPORT) {
822           FGAirport* apt = (FGAirport*) aPos;
823           if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
824             return false;
825           }
826         }
827       
828         return true;
829     }
830
831     virtual FGPositioned::Type minType() const {
832         return FGPositioned::AIRPORT;
833     }
834
835     virtual FGPositioned::Type maxType() const {
836         return FGPositioned::OBSTACLE;
837     }
838 };
839
840 void NavDisplay::findItems()
841 {
842     if (!_cachedItemsValid) {
843         SG_LOG(SG_INSTR, SG_INFO, "re-validating NavDisplay cache");
844         Filter filt;
845         filt.minRunwayLengthFt = 2000;
846         _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
847         _cachedItemsValid = true;
848         _cachedPos = SGVec3d::fromGeod(_pos);
849     }
850     
851     BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
852         foundPositionedItem(pos);
853     }
854 }
855
856 void NavDisplay::processRoute()
857 {
858     _routeSources.clear();
859     RoutePath path(_route->waypts());
860     int current = _route->currentIndex();
861     
862     for (int w=0; w<_route->numWaypts(); ++w) {
863         flightgear::WayptRef wpt(_route->wayptAtIndex(w));
864         _routeSources.insert(wpt->source());
865         
866         string_set state;
867         state.insert("on-active-route");
868         
869         if (w < current) {
870             state.insert("passed");
871         }
872         
873         if (w == current) {
874             state.insert("current-wp");
875         }
876         
877         if (w > current) {
878             state.insert("future");
879         }
880         
881         if (w == (current + 1)) {
882             state.insert("next-wp");
883         }
884         
885         SymbolDefVector rules;
886         findRules("waypoint" , state, rules);
887         if (rules.empty()) {
888             return; // no rules matched, we can skip this item
889         }
890
891         SGGeod g = path.positionForIndex(w);
892         SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
893         double heading;
894         computeWayptPropsAndHeading(wpt, g, vars, heading);
895
896         osg::Vec2 projected = projectGeod(g);
897         BOOST_FOREACH(SymbolDef* r, rules) {
898             addSymbolInstance(projected, heading, r, vars);
899             
900             if (r->drawRouteLeg) {
901                 SGGeodVec gv(path.pathForIndex(w));
902                 if (!gv.empty()) {
903                     osg::Vec2 pr = projectGeod(gv[0]);
904                     for (unsigned int i=1; i<gv.size(); ++i) {
905                         osg::Vec2 p = projectGeod(gv[i]);
906                         addLine(pr, p, r->lineColor);
907                         pr = p;
908                     }
909                 }
910             } // of leg drawing enabled
911         } // of matching rules iteration
912     } // of waypoints iteration
913 }
914
915 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
916 {
917     double rangeM, az2;
918     SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
919     nd->setIntValue("radial", heading);
920     nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
921     
922     heading = nd->getDoubleValue("leg-bearing-true-deg");
923 }
924
925 void NavDisplay::processNavRadios()
926 {
927     _nav1Station = processNavRadio(_navRadio1Node);
928     _nav2Station = processNavRadio(_navRadio2Node);
929     
930     foundPositionedItem(_nav1Station);
931     foundPositionedItem(_nav2Station);
932 }
933
934 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
935 {
936     double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
937     FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
938     if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
939         // station was not found
940         return NULL;
941     }
942     
943     
944     return nav;
945 }
946
947 bool NavDisplay::anyRuleForType(const string& type) const
948 {
949     BOOST_FOREACH(SymbolDef* r, _rules) {
950         if (!r->enabled) {
951             continue;
952         }
953     
954         if (r->type == type) {
955             return true;
956         }
957     }
958     
959     return false;
960 }
961
962 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
963 {
964     BOOST_FOREACH(SymbolDef* r, _rules) {
965         if (!r->enabled || (r->type != type)) {
966             continue;
967         }
968
969         if (r->matches(states)) {
970             return true;
971         }
972     } // of rules iteration
973     
974     return false;
975 }
976
977 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
978 {
979     BOOST_FOREACH(SymbolDef* candidate, _rules) {
980         if (!candidate->enabled || (candidate->type != type)) {
981             continue;
982         }
983         
984         if (candidate->matches(states)) {
985             rules.push_back(candidate);
986         }
987     }
988 }
989
990 void NavDisplay::foundPositionedItem(FGPositioned* pos)
991 {
992     if (!pos) {
993         return;
994     }
995     
996     string type = FGPositioned::nameForType(pos->type());
997     if (!anyRuleForType(type)) {
998         return; // not diplayed at all, we're done
999     }
1000     
1001     string_set states;
1002     computePositionedState(pos, states);
1003     
1004     SymbolDefVector rules;
1005     findRules(type, states, rules);
1006     if (rules.empty()) {
1007         return; // no rules matched, we can skip this item
1008     }
1009     
1010     SGPropertyNode_ptr vars(new SGPropertyNode);
1011     double heading;
1012     computePositionedPropsAndHeading(pos, vars, heading);
1013     
1014     osg::Vec2 projected = projectGeod(pos->geod());
1015     BOOST_FOREACH(SymbolDef* r, rules) {
1016         addSymbolInstance(projected, heading, r, vars);
1017     }
1018 }
1019
1020 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1021 {
1022     nd->setStringValue("id", pos->ident());
1023     nd->setStringValue("name", pos->name());
1024     nd->setDoubleValue("elevation-ft", pos->elevation());
1025     nd->setIntValue("heading-deg", 0);
1026     
1027     switch (pos->type()) {
1028     case FGPositioned::VOR:
1029     case FGPositioned::LOC: 
1030     case FGPositioned::TACAN: {
1031         FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1032         nd->setDoubleValue("frequency-mhz", nav->get_freq());
1033         
1034         if (pos == _nav1Station) {
1035             nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
1036         } else if (pos == _nav2Station) {
1037             nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
1038         }
1039         
1040         break;
1041     }
1042
1043     case FGPositioned::AIRPORT:
1044     case FGPositioned::SEAPORT:
1045     case FGPositioned::HELIPORT:
1046         
1047         break;
1048         
1049     case FGPositioned::RUNWAY: {
1050         FGRunway* rwy = static_cast<FGRunway*>(pos);
1051         nd->setDoubleValue("heading-deg", rwy->headingDeg());
1052         nd->setIntValue("length-ft", rwy->lengthFt());
1053         nd->setStringValue("airport", rwy->airport()->ident());
1054         break;
1055     }
1056
1057     default:
1058         break; 
1059     }
1060 }
1061
1062 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1063 {
1064     if (_routeSources.count(pos) != 0) {
1065         states.insert("on-active-route");
1066     }
1067     
1068     switch (pos->type()) {
1069     case FGPositioned::VOR:
1070     case FGPositioned::LOC:
1071         if (pos == _nav1Station) {
1072             states.insert("tuned");
1073             states.insert("nav1");
1074         }
1075         
1076         if (pos == _nav2Station) {
1077             states.insert("tuned");
1078             states.insert("nav2");
1079         }
1080         break;
1081     
1082     case FGPositioned::AIRPORT:
1083     case FGPositioned::SEAPORT:
1084     case FGPositioned::HELIPORT:
1085         // mark alternates!
1086         // once the FMS system has some way to tell us about them, of course
1087         
1088         if (pos == _route->departureAirport()) {
1089             states.insert("departure");
1090         }
1091         
1092         if (pos == _route->destinationAirport()) {
1093             states.insert("destination");
1094         }
1095         break;
1096     
1097     case FGPositioned::RUNWAY:
1098         if (pos == _route->departureRunway()) {
1099             states.insert("departure");
1100         }
1101         
1102         if (pos == _route->destinationRunway()) {
1103             states.insert("destination");
1104         }
1105         break;
1106     
1107     case FGPositioned::OBSTACLE:
1108     #if 0    
1109         FGObstacle* obs = (FGObstacle*) pos;
1110         if (obj->isLit()) {
1111             states.insert("lit");
1112         }
1113         
1114         if (obj->getHeightAGLFt() >= 1000) {
1115             states.insert("greater-1000-ft");
1116         }
1117     #endif
1118         break;
1119     
1120     default:
1121         break;
1122     } // FGPositioned::Type switch
1123 }
1124
1125 void NavDisplay::processAI()
1126 {
1127     SGPropertyNode *ai = fgGetNode("/ai/models", true);
1128     for (int i = ai->nChildren() - 1; i >= 0; i--) {
1129         SGPropertyNode *model = ai->getChild(i);
1130         if (!model->nChildren()) {
1131             continue;
1132         }
1133         
1134     // prefix types with 'ai-', to avoid any chance of namespace collisions
1135     // with fg-positioned.
1136         string_set ss;
1137         computeAIStates(model, ss);        
1138         SymbolDefVector rules;
1139         findRules(string("ai-") + model->getName(), ss, rules);
1140         if (rules.empty()) {
1141             return; // no rules matched, we can skip this item
1142         }
1143
1144         double heading = model->getDoubleValue("orientation/true-heading-deg");
1145         SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"), 
1146                                             model->getDoubleValue("position/latitude-deg"), 
1147                                             model->getDoubleValue("position/altitude-ft"));
1148     // compute some additional props
1149         int fl = (aiModelPos.getElevationFt() / 1000);
1150         model->setIntValue("flight-level", fl * 10);
1151                                             
1152         osg::Vec2 projected = projectGeod(aiModelPos);
1153         BOOST_FOREACH(SymbolDef* r, rules) {
1154             addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1155         }
1156     } // of ai models iteration
1157 }
1158
1159 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1160 {
1161     int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1162     if (threatLevel >= 0) {
1163         states.insert("tcas");
1164       
1165         std::ostringstream os;
1166         os << "tcas-threat-level-" << threatLevel;
1167         states.insert(os.str());
1168     }
1169     
1170     double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1171     if (vspeed < -3.0) {
1172         states.insert("descending");
1173     } else if (vspeed > 3.0) {
1174         states.insert("climbing");
1175     }
1176 }
1177
1178 bool NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1179 {
1180     if (isProjectedClipped(proj)) {
1181         return false;
1182     }
1183     
1184     SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1185     _symbols.push_back(sym);
1186     return true;
1187 }
1188
1189 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1190 {
1191     double size = _odg->size();
1192     return (projected.x() < 0.0) ||
1193         (projected.y() < 0.0) ||
1194         (projected.x() >= size) ||
1195             (projected.y() >= size);
1196 }
1197
1198 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1199 {
1200   string_set stateSet;
1201   BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1202     stateSet.insert(s);
1203   }
1204   
1205   SymbolDefVector rules;
1206   findRules(type, stateSet, rules);
1207   if (rules.empty()) {
1208     return; // no rules matched, we can skip this item
1209   }
1210     
1211   osg::Vec2 projected = projectGeod(pos);
1212   BOOST_FOREACH(SymbolDef* r, rules) {
1213     addSymbolInstance(projected, heading, r, vars);
1214   }
1215 }
1216
1217 void NavDisplay::addTestSymbols()
1218 {
1219   _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1220   
1221   SGGeod a1;
1222   double dummy;
1223   SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1224   
1225   addTestSymbol("airport", "", a1, 0.0, NULL);
1226   
1227   SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1228   
1229   addTestSymbol("vor", "", a1, 0.0, NULL);
1230   
1231   SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1232   
1233   addTestSymbol("airport", "destination", a1, 0.0, NULL);
1234   
1235   SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1236   addTestSymbol("fix", "", a1, 0.0, NULL);
1237
1238   
1239   SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1240   addTestSymbol("fix", "", a1, 0.0, NULL);
1241   
1242   SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);  
1243   addTestSymbol("fix", "", a1, 0.0, NULL);
1244   
1245   SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);  
1246   addTestSymbol("fix", "", a1, 0.0, NULL);
1247 }
1248
1249