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