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