]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
And expose the published navaid range to Nasal, since we can.
[flightgear.git] / src / Scripting / NasalPositioned.cxx
1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
2 //
3 // Written by James Turner, started 2012.
4 //
5 // Copyright (C) 2012 James Turner
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <string.h>
26
27 #include "NasalPositioned.hxx"
28
29 #include <boost/foreach.hpp>
30
31 #include <simgear/sg_inlines.h>
32 #include <simgear/scene/material/mat.hxx>
33 #include <simgear/magvar/magvar.hxx>
34 #include <simgear/timing/sg_time.hxx>
35 #include <simgear/bucket/newbucket.hxx>
36
37 #include <Airports/runways.hxx>
38 #include <Airports/simple.hxx>
39 #include <Airports/dynamics.hxx>
40 #include <Airports/parking.hxx>
41 #include <Navaids/navlist.hxx>
42 #include <Navaids/procedure.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <ATC/CommStation.hxx>
47 #include <Navaids/route.hxx>
48 #include <Autopilot/route_mgr.hxx>
49 #include <Navaids/procedure.hxx>
50
51 static void positionedGhostDestroy(void* g);
52 static void wayptGhostDestroy(void* g);
53 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
54
55 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
56 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
57
58 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
59 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
60
61 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
62 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
63
64 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
65
66 naGhostType WayptGhostType = { wayptGhostDestroy, 
67   "waypoint",
68   wayptGhostGetMember,
69   0};
70
71 static void hashset(naContext c, naRef hash, const char* key, naRef val)
72 {
73   naRef s = naNewString(c);
74   naStr_fromdata(s, (char*)key, strlen(key));
75   naHash_set(hash, s, val);
76 }
77
78 static naRef stringToNasal(naContext c, const std::string& s)
79 {
80     return naStr_fromdata(naNewString(c),
81                    const_cast<char *>(s.c_str()), 
82                    s.length());
83 }
84
85 static FGPositioned* positionedGhost(naRef r)
86 {
87     if (naGhost_type(r) == &PositionedGhostType)
88         return (FGPositioned*) naGhost_ptr(r);
89     return 0;
90 }
91
92 static FGAirport* airportGhost(naRef r)
93 {
94   if (naGhost_type(r) == &AirportGhostType)
95     return (FGAirport*) naGhost_ptr(r);
96   return 0;
97 }
98
99 static FGNavRecord* navaidGhost(naRef r)
100 {
101   if (naGhost_type(r) == &NavaidGhostType)
102     return (FGNavRecord*) naGhost_ptr(r);
103   return 0;
104 }
105
106 static FGRunway* runwayGhost(naRef r)
107 {
108   if (naGhost_type(r) == &RunwayGhostType)
109     return (FGRunway*) naGhost_ptr(r);
110   return 0;
111 }
112
113 static void positionedGhostDestroy(void* g)
114 {
115     FGPositioned* pos = (FGPositioned*)g;
116     if (!FGPositioned::put(pos)) // unref
117         delete pos;
118 }
119
120 static flightgear::Waypt* wayptGhost(naRef r)
121 {
122   if (naGhost_type(r) == &WayptGhostType)
123     return (flightgear::Waypt*) naGhost_ptr(r);
124   return 0;
125 }
126
127 static void wayptGhostDestroy(void* g)
128 {
129   flightgear::Waypt* wpt = (flightgear::Waypt*)g;
130   if (!flightgear::Waypt::put(wpt)) // unref
131     delete wpt;
132 }
133
134 static naRef airportPrototype;
135 static naRef routePrototype;
136 static naRef waypointPrototype;
137 static naRef geoCoordClass;
138
139 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
140 {
141     if (!pos) {
142         return naNil();
143     }
144     
145     FGPositioned::get(pos); // take a ref
146     return naNewGhost(c, &PositionedGhostType, (void*) pos);
147 }
148
149 naRef ghostForAirport(naContext c, const FGAirport* apt)
150 {
151   if (!apt) {
152     return naNil();
153   }
154   
155   FGPositioned::get(apt); // take a ref
156   return naNewGhost2(c, &AirportGhostType, (void*) apt);
157 }
158
159 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
160 {
161   if (!n) {
162     return naNil();
163   }
164   
165   FGPositioned::get(n); // take a ref
166   return naNewGhost2(c, &NavaidGhostType, (void*) n);
167 }
168
169 naRef ghostForRunway(naContext c, const FGRunway* r)
170 {
171   if (!r) {
172     return naNil();
173   }
174   
175   FGPositioned::get(r); // take a ref
176   return naNewGhost2(c, &RunwayGhostType, (void*) r);
177 }
178
179 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
180 {
181   if (!wpt) {
182     return naNil();
183   }
184   
185   flightgear::Waypt::get(wpt); // take a ref
186   return naNewGhost2(c, &WayptGhostType, (void*) wpt);
187 }
188
189 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
190 {
191   const char* fieldName = naStr_data(field);
192   FGAirport* apt = (FGAirport*) g;
193   
194   if (!strcmp(fieldName, "parents")) {
195     *out = naNewVector(c);
196     naVec_append(*out, airportPrototype);
197   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
198   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
199   else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
200   else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
201   else if (!strcmp(fieldName, "elevation")) {
202     *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
203   } else if (!strcmp(fieldName, "has_metar")) {
204     *out = naNum(apt->getMetar());
205   } else if (!strcmp(fieldName, "runways")) {
206     *out = naNewHash(c);
207     for(unsigned int r=0; r<apt->numRunways(); ++r) {
208       FGRunway* rwy(apt->getRunwayByIndex(r));
209       naRef rwyid = stringToNasal(c, rwy->ident());
210       naRef rwydata = ghostForRunway(c, rwy);
211       naHash_set(*out, rwyid, rwydata);
212     }
213
214   } else {
215     return 0;
216   }
217   
218   return "";
219 }
220
221 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
222 {
223   const char* fieldName = naStr_data(field);
224   flightgear::Waypt* wpt = (flightgear::Waypt*) g;
225
226   if (!strcmp(fieldName, "parents")) {
227     *out = naNewVector(c);
228     naVec_append(*out, waypointPrototype);
229   } else if (!strcmp(fieldName, "wp_name")) *out =stringToNasal(c, wpt->ident());
230   else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
231   else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
232   else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
233   else if (!strcmp(fieldName, "wp_parent_name")) {
234     flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
235     *out = proc ? stringToNasal(c, proc->ident()) : naNil();
236   } else if (!strcmp(fieldName, "fly_type")) {
237     if (wpt->type() == "hold") {
238       *out = stringToNasal(c, "Hold");
239     } else {
240       *out = stringToNasal(c, wpt->flag(flightgear::WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
241     }
242   } else if (!strcmp(fieldName, "alt_cstr")) *out = naNum(wpt->altitudeFt());
243   else if (!strcmp(fieldName, "speed_cstr")) {
244     double s = (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) 
245       ? wpt->speedMach() : wpt->speedKts();
246     *out = naNum(s);
247   } else if (!strcmp(fieldName, "leg_distance")) {
248     return "please implement me";
249   } else if (!strcmp(fieldName, "leg_bearing")) {
250     return "please implement me";
251   } else {
252     return NULL; // member not found
253   }
254   
255   return ""; // success
256 }
257
258 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
259 {
260   const char* fieldName = naStr_data(field);
261   FGRunway* rwy = (FGRunway*) g;
262   
263   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
264   else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
265   else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
266   else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
267   else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
268   else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
269   else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
270   else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
271   else if (!strcmp(fieldName, "ils_frequency_mhz")) {
272     *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
273   } else if (!strcmp(fieldName, "ils")) {
274     *out = ghostForNavaid(c, rwy->ILS());
275   } else {
276     return 0;
277   }
278   
279   return "";
280 }
281
282 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
283 {
284   const char* fieldName = naStr_data(field);
285   FGNavRecord* nav = (FGNavRecord*) g;
286   
287   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
288   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
289   else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
290   else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
291   else if (!strcmp(fieldName, "elevation")) {
292     *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
293   } else if (!strcmp(fieldName, "type")) {
294     *out = stringToNasal(c, nav->nameForType(nav->type()));
295   } else if (!strcmp(fieldName, "frequency")) {
296     *out = naNum(nav->get_freq()); 
297   } else if (!strcmp(fieldName, "range_nm")) {
298     *out = naNum(nav->get_range()); 
299   } else if (!strcmp(fieldName, "course")) {
300     if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
301       double radial = nav->get_multiuse();
302       SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
303       *out = naNum(radial);
304     } else {
305       *out = naNil();
306     }
307   } else {
308     return 0;
309   }
310   
311   return "";
312 }
313
314 static bool hashIsCoord(naRef h)
315 {
316   naRef parents = naHash_cget(h, (char*) "parents");
317   if (!naIsVector(parents)) {
318     return false;
319   }
320   
321   return naEqual(naVec_get(parents, 0), geoCoordClass);
322 }
323
324 bool geodFromHash(naRef ref, SGGeod& result)
325 {
326   if (!naIsHash(ref)) {
327     return false;
328   }
329   
330 // first, see if the hash contains a FGPositioned ghost - in which case
331 // we can read off its position directly
332   naRef posGhost = naHash_cget(ref, (char*) "_positioned");
333   if (!naIsNil(posGhost)) {
334     FGPositioned* pos = positionedGhost(posGhost);
335     result = pos->geod();
336     return true;
337   }
338   
339 // then check for manual latitude / longitude names
340   naRef lat = naHash_cget(ref, (char*) "lat");
341   naRef lon = naHash_cget(ref, (char*) "lon");
342   if (naIsNum(lat) && naIsNum(lon)) {
343     result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
344     return true;
345   }
346   
347   if (hashIsCoord(ref)) {
348     naRef lat = naHash_cget(ref, (char*) "_lat");
349     naRef lon = naHash_cget(ref, (char*) "_lon");
350     if (naIsNum(lat) && naIsNum(lon)) {
351       result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
352       return true;
353     }
354   }
355     
356 // check for any synonyms?
357     // latitude + longitude?
358   
359   return false;
360 }
361
362 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
363 {
364   if (offset >= argc) {
365     return 0;
366   }
367   
368   if (naIsGhost(args[offset])) {
369     naGhostType* gt = naGhost_type(args[offset]);
370     if (gt == &AirportGhostType) {
371       result = airportGhost(args[offset])->geod();
372       return 1;
373     }
374     
375     if (gt == &NavaidGhostType) {
376       result = navaidGhost(args[offset])->geod();
377       return 1;
378     }
379     
380     if (gt == &RunwayGhostType) {
381       result = runwayGhost(args[offset])->geod();
382       return 1;
383     }
384     
385     if (gt == &WayptGhostType) {
386       result = wayptGhost(args[offset])->position();
387       return 1;
388     }
389   }
390   
391   if (geodFromHash(args[offset], result)) {
392     return 1;
393   }
394   
395   if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
396     double lat = naNumValue(args[0]).num,
397     lon = naNumValue(args[1]).num;
398     result = SGGeod::fromDeg(lon, lat);
399     return 2;
400   }
401   
402   return 0;
403 }
404
405 // Convert a cartesian point to a geodetic lat/lon/altitude.
406 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
407 {
408   double lat, lon, alt, xyz[3];
409   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
410   for(int i=0; i<3; i++)
411     xyz[i] = naNumValue(args[i]).num;
412   sgCartToGeod(xyz, &lat, &lon, &alt);
413   lat *= SG_RADIANS_TO_DEGREES;
414   lon *= SG_RADIANS_TO_DEGREES;
415   naRef vec = naNewVector(c);
416   naVec_append(vec, naNum(lat));
417   naVec_append(vec, naNum(lon));
418   naVec_append(vec, naNum(alt));
419   return vec;
420 }
421
422 // Convert a geodetic lat/lon/altitude to a cartesian point.
423 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
424 {
425   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
426   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
427   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
428   double alt = naNumValue(args[2]).num;
429   double xyz[3];
430   sgGeodToCart(lat, lon, alt, xyz);
431   naRef vec = naNewVector(c);
432   naVec_append(vec, naNum(xyz[0]));
433   naVec_append(vec, naNum(xyz[1]));
434   naVec_append(vec, naNum(xyz[2]));
435   return vec;
436 }
437
438 // For given geodetic point return array with elevation, and a material data
439 // hash, or nil if there's no information available (tile not loaded). If
440 // information about the material isn't available, then nil is returned instead
441 // of the hash.
442 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
443 {
444 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
445   if(argc < 2 || argc > 3)
446     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
447   double lat = naNumValue(args[0]).num;
448   double lon = naNumValue(args[1]).num;
449   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
450   const SGMaterial *mat;
451   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
452   if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
453     return naNil();
454   naRef vec = naNewVector(c);
455   naVec_append(vec, naNum(elev));
456   naRef matdata = naNil();
457   if(mat) {
458     matdata = naNewHash(c);
459     naRef names = naNewVector(c);
460     BOOST_FOREACH(const std::string& n, mat->get_names())
461       naVec_append(names, stringToNasal(c, n));
462       
463     HASHSET("names", 5, names);
464     HASHSET("solid", 5, naNum(mat->get_solid()));
465     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
466     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
467     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
468     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
469     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
470   }
471   naVec_append(vec, matdata);
472   return vec;
473 #undef HASHSET
474 }
475
476
477 class AirportInfoFilter : public FGAirport::AirportFilter
478 {
479 public:
480   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
481   }
482   
483   bool fromArg(naRef arg)
484   {
485     const char *s = naStr_data(arg);
486     if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
487     else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
488     else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
489     else
490       return false;
491     
492     return true;
493   }
494   
495   virtual FGPositioned::Type minType() const {
496     return type;
497   }
498   
499   virtual FGPositioned::Type maxType() const {
500     return type;
501   }
502   
503   FGPositioned::Type type;
504 };
505
506 // Returns data hash for particular or nearest airport of a <type>, or nil
507 // on error.
508 //
509 // airportinfo(<id>);                   e.g. "KSFO"
510 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
511 // airportinfo()                        same as  airportinfo("airport")
512 // airportinfo(<lat>, <lon> [, <type>]);
513 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
514 {
515   SGGeod pos = globals->get_aircraft_position();
516   FGAirport* apt = NULL;
517   
518   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
519     pos = SGGeod::fromDeg(args[1].num, args[0].num);
520     args += 2;
521     argc -= 2;
522   }
523   
524   double maxRange = 10000.0; // expose this? or pick a smaller value?
525   
526   AirportInfoFilter filter; // defaults to airports only
527   
528   if(argc == 0) {
529     // fall through and use AIRPORT
530   } else if(argc == 1 && naIsString(args[0])) {
531     if (filter.fromArg(args[0])) {
532       // done!
533     } else {
534       // user provided an <id>, hopefully
535       apt = FGAirport::findByIdent(naStr_data(args[0]));
536       if (!apt) {
537         // return nil here, but don't raise a runtime error; this is a
538         // legitamate way to validate an ICAO code, for example in a
539         // dialog box or similar.
540         return naNil();
541       }
542     }
543   } else {
544     naRuntimeError(c, "airportinfo() with invalid function arguments");
545     return naNil();
546   }
547   
548   if(!apt) {
549     apt = FGAirport::findClosest(pos, maxRange, &filter);
550     if(!apt) return naNil();
551   }
552   
553   return ghostForAirport(c, apt);
554 }
555
556 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
557 {
558   int argOffset = 0;
559   SGGeod pos = globals->get_aircraft_position();
560   argOffset += geodFromArgs(args, 0, argc, pos);
561   
562   if (!naIsNum(args[argOffset])) {
563     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
564   }
565   
566   AirportInfoFilter filter; // defaults to airports only
567   double rangeNm = args[argOffset++].num;
568   if (argOffset < argc) {
569     filter.fromArg(args[argOffset++]);
570   }
571   
572   naRef r = naNewVector(c);
573   
574   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
575   FGPositioned::sortByRange(apts, pos);
576   
577   BOOST_FOREACH(FGPositionedRef a, apts) {
578     FGAirport* apt = (FGAirport*) a.get();
579     naVec_append(r, ghostForAirport(c, apt));
580   }
581   
582   return r;
583 }
584
585 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
586 {
587   if (!naIsString(args[0])) {
588     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
589   }
590   
591   int argOffset = 0;
592   string prefix(naStr_data(args[argOffset++]));
593   AirportInfoFilter filter; // defaults to airports only
594   if (argOffset < argc) {
595     filter.fromArg(args[argOffset++]);
596   }
597   
598   naRef r = naNewVector(c);
599   
600   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
601   
602   BOOST_FOREACH(FGPositionedRef a, apts) {
603     FGAirport* apt = (FGAirport*) a.get();
604     naVec_append(r, ghostForAirport(c, apt));
605   }
606   
607   return r;
608 }
609
610 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
611 {
612     FGAirport* apt = airportGhost(me);
613     if (!apt) {
614       naRuntimeError(c, "airport.tower called on non-airport object");
615     }
616   
617     // build a hash for the tower position    
618     SGGeod towerLoc = apt->getTowerLocation();
619     naRef tower = naNewHash(c);
620     hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
621     hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
622     hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
623     return tower;
624 }
625
626 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
627 {
628     FGAirport* apt = airportGhost(me);
629     if (!apt) {
630       naRuntimeError(c, "airport.comms called on non-airport object");
631     }
632     naRef comms = naNewVector(c);
633     
634 // if we have an explicit type, return a simple vector of frequencies
635     if (argc > 0 && naIsScalar(args[0])) {
636         std::string commName = naStr_data(args[0]);
637         FGPositioned::Type commType = FGPositioned::typeFromName(commName);
638         
639         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
640             naVec_append(comms, naNum(comm->freqMHz()));
641         }
642     } else {
643 // otherwise return a vector of hashes, one for each comm station.
644         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
645             naRef commHash = naNewHash(c);
646             hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
647             hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
648             naVec_append(comms, commHash);
649         }
650     }
651     
652     return comms;
653 }
654
655 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
656 {
657   FGAirport* apt = airportGhost(me);
658   if (!apt) {
659     naRuntimeError(c, "airport.runway called on non-airport object");
660   }
661   
662   if ((argc < 1) || !naIsString(args[0])) {
663     naRuntimeError(c, "airport.runway expects a runway ident argument");
664   }
665   
666   std::string ident(naStr_data(args[0]));
667   if (!apt->hasRunwayWithIdent(ident)) {
668     return naNil();
669   }
670   
671   return ghostForRunway(c, apt->getRunwayByIdent(ident));
672 }
673
674 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
675 {
676   FGAirport* apt = airportGhost(me);
677   if (!apt) {
678     naRuntimeError(c, "airport.sids called on non-airport object");
679   }
680   
681   naRef sids = naNewVector(c);
682   
683   if (argc > 0 && naIsString(args[0])) {
684     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
685       return naNil();
686     }
687
688     FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
689     BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
690       naRef procId = stringToNasal(c, sid->ident());
691       naVec_append(sids, procId);
692     }
693   } else {
694     for (unsigned int s=0; s<apt->numSIDs(); ++s) {
695       flightgear::SID* sid = apt->getSIDByIndex(s);
696       naRef procId = stringToNasal(c, sid->ident());
697       naVec_append(sids, procId);
698     }
699   }
700   
701   return sids;
702 }
703
704 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
705 {
706   FGAirport* apt = airportGhost(me);
707   if (!apt) {
708     naRuntimeError(c, "airport.stars called on non-airport object");
709   }
710   
711   naRef stars = naNewVector(c);
712   
713   if (argc > 0 && naIsString(args[0])) {
714     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
715       return naNil();
716     }
717         
718     FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
719     BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
720       naRef procId = stringToNasal(c, s->ident());
721       naVec_append(stars, procId);
722     }
723   } else {
724     for (unsigned int s=0; s<apt->numSTARs(); ++s) {
725       flightgear::STAR* star = apt->getSTARByIndex(s);
726       naRef procId = stringToNasal(c, star->ident());
727       naVec_append(stars, procId);
728     }
729   }
730   
731   return stars;
732 }
733
734 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
735 {
736   FGAirport* apt = airportGhost(me);
737   if (!apt) {
738     naRuntimeError(c, "airport.parking called on non-airport object");
739   }
740   
741   naRef r = naNewVector(c);
742   std::string type;
743   bool onlyAvailable = false;
744   
745   if (argc > 0 && naIsString(args[0])) {
746     type = naStr_data(args[0]);
747   }
748   
749   if ((argc > 1) && naIsNum(args[1])) {
750     onlyAvailable = (args[1].num != 0.0);
751   }
752   
753   FGAirportDynamics* dynamics = apt->getDynamics();
754   for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
755     FGParking* park = dynamics->getParking(i);
756   // filter out based on availability and type
757     if (onlyAvailable && !park->isAvailable()) {
758       continue;
759     }
760     
761     if (!type.empty() && (park->getType() != type)) {
762       continue;
763     }
764     
765     naRef nm = stringToNasal(c, park->getName());
766     naVec_append(r, nm);
767   }
768   
769   return r;
770 }
771
772 // Returns vector of data hash for navaid of a <type>, nil on error
773 // navaids sorted by ascending distance 
774 // navinfo([<lat>,<lon>],[<type>],[<id>])
775 // lat/lon (numeric): use latitude/longitude instead of ac position
776 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
777 // id:                (partial) id of the fix
778 // examples:
779 // navinfo("vor")     returns all vors
780 // navinfo("HAM")     return all navaids who's name start with "HAM"
781 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
782 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
783 //                           sorted by distance relative to lat=34, lon=48
784 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
785 {
786   SGGeod pos;
787   
788   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
789     pos = SGGeod::fromDeg(args[1].num, args[0].num);
790     args += 2;
791     argc -= 2;
792   } else {
793     pos = globals->get_aircraft_position();
794   }
795   
796   FGPositioned::Type type = FGPositioned::INVALID;
797   nav_list_type navlist;
798   const char * id = "";
799   
800   if(argc > 0 && naIsString(args[0])) {
801     const char *s = naStr_data(args[0]);
802     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
803     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
804     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
805     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
806     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
807     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
808     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
809     else id = s; // this is an id
810     ++args;
811     --argc;
812   } 
813   
814   if(argc > 0 && naIsString(args[0])) {
815     if( *id != 0 ) {
816       naRuntimeError(c, "navinfo() called with navaid id");
817       return naNil();
818     }
819     id = naStr_data(args[0]);
820     ++args;
821     --argc;
822   }
823   
824   if( argc > 0 ) {
825     naRuntimeError(c, "navinfo() called with too many arguments");
826     return naNil();
827   }
828   
829   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
830   
831   naRef reply = naNewVector(c);
832   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
833     naVec_append( reply, ghostForNavaid(c, *it) );
834   }
835   return reply;
836 }
837
838 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
839 {
840   int argOffset = 0;
841   SGGeod pos = globals->get_aircraft_position();
842   argOffset += geodFromArgs(args, 0, argc, pos);
843   
844   if (!naIsNum(args[argOffset])) {
845     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
846   }
847   
848   FGPositioned::Type type = FGPositioned::INVALID;
849   double rangeNm = args[argOffset++].num;
850   if (argOffset < argc) {
851     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
852   }
853   
854   naRef r = naNewVector(c);
855   FGNavList::TypeFilter filter(type);
856   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
857   FGPositioned::sortByRange(navs, pos);
858   
859   BOOST_FOREACH(FGPositionedRef a, navs) {
860     FGNavRecord* nav = (FGNavRecord*) a.get();
861     naVec_append(r, ghostForNavaid(c, nav));
862   }
863   
864   return r;
865 }
866
867 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
868 {
869   int argOffset = 0;
870   SGGeod pos = globals->get_aircraft_position();
871   argOffset += geodFromArgs(args, 0, argc, pos);
872   
873   if (!naIsNum(args[argOffset])) {
874     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
875   }
876   
877   FGPositioned::Type type = FGPositioned::INVALID;
878   double freqMhz = args[argOffset++].num;
879   if (argOffset < argc) {
880     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
881   }
882   
883   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
884   if (navs.empty()) {
885     return naNil();
886   }
887   
888   return ghostForNavaid(c, navs.front().ptr());
889 }
890
891 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
892 {
893   int argOffset = 0;
894   SGGeod pos = globals->get_aircraft_position();
895   argOffset += geodFromArgs(args, 0, argc, pos);
896   
897   if (!naIsNum(args[argOffset])) {
898     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
899   }
900   
901   FGPositioned::Type type = FGPositioned::INVALID;
902   double freqMhz = args[argOffset++].num;
903   if (argOffset < argc) {
904     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
905   }
906   
907   naRef r = naNewVector(c);
908   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
909   
910   BOOST_FOREACH(nav_rec_ptr a, navs) {
911     naVec_append(r, ghostForNavaid(c, a.ptr()));
912   }
913   
914   return r;
915 }
916
917 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
918 {
919   int argOffset = 0;
920   SGGeod pos = globals->get_aircraft_position();
921   argOffset += geodFromArgs(args, 0, argc, pos);
922   
923   if (!naIsString(args[argOffset])) {
924     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
925   }
926   
927   FGPositioned::Type type = FGPositioned::INVALID;
928   string ident = naStr_data(args[argOffset++]);
929   if (argOffset < argc) {
930     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
931   }
932   
933   naRef r = naNewVector(c);
934   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
935   
936   BOOST_FOREACH(nav_rec_ptr a, navs) {
937     naVec_append(r, ghostForNavaid(c, a.ptr()));
938   }
939   
940   return r;
941 }
942
943
944 // Convert a cartesian point to a geodetic lat/lon/altitude.
945 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
946 {
947   SGGeod pos = globals->get_aircraft_position();
948   if (argc == 0) {
949     // fine, use aircraft position
950   } else if (geodFromArgs(args, 0, argc, pos)) {
951     // okay
952   } else {
953     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
954   }
955   
956   double jd = globals->get_time_params()->getJD();
957   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
958   return naNum(magvarDeg);
959 }
960
961 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
962 {
963     SGGeod from = globals->get_aircraft_position(), to, p;
964     int argOffset = geodFromArgs(args, 0, argc, p);
965     if (geodFromArgs(args, argOffset, argc, to)) {
966       from = p; // we parsed both FROM and TO args, so first was from
967     } else {
968       to = p; // only parsed one arg, so FROM is current
969     }
970   
971     if (argOffset == 0) {
972         naRuntimeError(c, "invalid arguments to courseAndDistance");
973     }
974     
975     double course, course2, d;
976     SGGeodesy::inverse(from, to, course, course2, d);
977     
978     naRef result = naNewVector(c);
979     naVec_append(result, naNum(course));
980     naVec_append(result, naNum(d * SG_METER_TO_NM));
981     return result;
982 }
983
984 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
985 {
986   SGGeod from = globals->get_aircraft_position(), to;
987   int argOffset = 0;
988   
989   // complication - don't inerpret two doubles (as the only args)
990   // as a lat,lon pair - only do so if we have at least three args.
991   if (argc > 2) {
992     argOffset = geodFromArgs(args, 0, argc, from);
993   }
994   
995   if ((argOffset + 1) >= argc) {
996     naRuntimeError(c, "isufficent arguments to greatCircleMove");
997   }
998   
999   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1000     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1001                    argOffset, argOffset + 1);
1002   }
1003   
1004   double course = args[argOffset].num, course2;
1005   double distanceNm = args[argOffset + 1].num;
1006   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1007   
1008   // return geo.Coord
1009   naRef coord = naNewHash(c);
1010   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1011   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1012   return coord;
1013 }
1014
1015 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1016 {
1017     SGGeod pos = globals->get_aircraft_position();
1018     geodFromArgs(args, 0, argc, pos);
1019     SGBucket b(pos);
1020     return stringToNasal(c, b.gen_base_path());
1021 }
1022
1023 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1024 {
1025   SGGeod pos = globals->get_aircraft_position();
1026   geodFromArgs(args, 0, argc, pos);
1027   SGBucket b(pos);
1028   return naNum(b.gen_index());
1029 }
1030
1031 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1032 {
1033   naRef route = naNewHash(c);
1034   
1035   // return active route hash by default,
1036   // other routes in the future
1037   
1038   naRef parents = naNewVector(c);
1039   naVec_append(parents, routePrototype);
1040   hashset(c, route, "parents", parents);
1041   
1042   return route;
1043 }
1044
1045 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
1046 {
1047   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1048   
1049   int index;
1050   if (argc == 0) {
1051     index = rm->currentIndex();
1052   } else {
1053     index = (int) naNumValue(args[0]).num;
1054   }
1055   
1056   if ((index < 0) || (index >= rm->numWaypts())) {
1057     return naNil();
1058   }
1059   
1060   return ghostForWaypt(c, rm->wayptAtIndex(index));
1061 }
1062
1063 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
1064 {
1065   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1066   return ghostForWaypt(c, rm->currentWaypt());
1067 }
1068
1069 static naRef f_route_nextWP(naContext c, naRef me, int argc, naRef* args)
1070 {
1071   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1072   flightgear::WayptRef wp = rm->nextWaypt();
1073   if (!wp) {
1074     return naNil();
1075   }
1076   return ghostForWaypt(c, wp);
1077 }
1078
1079 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
1080 {
1081   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1082   return naNum(rm->currentIndex());
1083 }
1084
1085 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1086 {
1087   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1088   return naNum(rm->numWaypts());
1089 }
1090
1091 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1092 {
1093   flightgear::Waypt* w = wayptGhost(me);
1094   if (!w) {
1095     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1096   }
1097   
1098   FGPositioned* pos = w->source();
1099   if (!pos) {
1100     return naNil();
1101   }
1102   
1103   switch (pos->type()) {
1104   case FGPositioned::VOR:
1105   case FGPositioned::NDB:
1106   case FGPositioned::ILS:
1107   case FGPositioned::LOC:
1108   case FGPositioned::GS:
1109   case FGPositioned::DME:
1110   case FGPositioned::TACAN: {
1111     FGNavRecord* nav = (FGNavRecord*) pos;
1112     return ghostForNavaid(c, nav);
1113   }
1114       
1115   default:
1116     return naNil();
1117   }
1118 }
1119
1120 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1121 {
1122   flightgear::Waypt* w = wayptGhost(me);
1123   if (!w) {
1124     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1125   }
1126   
1127   FGPositioned* pos = w->source();
1128   if (!pos || FGAirport::isAirportType(pos)) {
1129     return naNil();
1130   }
1131   
1132   return ghostForAirport(c, (FGAirport*) pos);
1133 }
1134
1135 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1136 {
1137   flightgear::Waypt* w = wayptGhost(me);
1138   if (!w) {
1139     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1140   }
1141   
1142   FGPositioned* pos = w->source();
1143   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1144     return naNil();
1145   }
1146   
1147   return ghostForRunway(c, (FGRunway*) pos);
1148 }
1149
1150 // Table of extension functions.  Terminate with zeros.
1151 static struct { const char* name; naCFunction func; } funcs[] = {
1152   { "carttogeod", f_carttogeod },
1153   { "geodtocart", f_geodtocart },
1154   { "geodinfo", f_geodinfo },
1155   { "airportinfo", f_airportinfo },
1156   { "findAirportsWithinRange", f_findAirportsWithinRange },
1157   { "findAirportsByICAO", f_findAirportsByICAO },
1158   { "navinfo", f_navinfo },
1159   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1160   { "findNavaidByFrequency", f_findNavaidByFrequency },
1161   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1162   { "findNavaidsByID", f_findNavaidsByIdent },
1163   { "route", f_route },
1164   { "magvar", f_magvar },
1165   { "courseAndDistance", f_courseAndDistance },
1166   { "greatCircleMove", f_greatCircleMove },
1167   { "tileIndex", f_tileIndex },
1168   { "tilePath", f_tilePath },
1169   { 0, 0 }
1170 };
1171
1172
1173 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1174 {
1175     airportPrototype = naNewHash(c);
1176     hashset(c, gcSave, "airportProto", airportPrototype);
1177   
1178     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
1179     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1180     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1181     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1182     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1183     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1184   
1185     routePrototype = naNewHash(c);
1186     hashset(c, gcSave, "routeProto", routePrototype);
1187       
1188     hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1189     hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP))); 
1190     hashset(c, routePrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_route_nextWP))); 
1191     hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1192     hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1193     
1194     waypointPrototype = naNewHash(c);
1195     hashset(c, gcSave, "wayptProto", waypointPrototype);
1196     
1197     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1198     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1199     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1200   
1201     for(int i=0; funcs[i].name; i++) {
1202       hashset(c, globals, funcs[i].name,
1203       naNewFunc(c, naNewCCode(c, funcs[i].func)));
1204     }
1205   
1206   return naNil();
1207 }
1208
1209 void postinitNasalPositioned(naRef globals, naContext c)
1210 {
1211   naRef geoModule = naHash_cget(globals, (char*) "geo");
1212   if (naIsNil(geoModule)) {
1213     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
1214     return;
1215   }
1216   
1217   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
1218 }
1219
1220