]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
Visual Studio bug workaround
[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 #include <boost/algorithm/string/case_conv.hpp>
31
32 #include <simgear/sg_inlines.h>
33 #include <simgear/scene/material/mat.hxx>
34 #include <simgear/magvar/magvar.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/bucket/newbucket.hxx>
37
38 #include <Airports/runways.hxx>
39 #include <Airports/simple.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/parking.hxx>
42 #include <Scripting/NasalSys.hxx>
43 #include <Navaids/navlist.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Scenery/scenery.hxx>
48 #include <ATC/CommStation.hxx>
49 #include <Navaids/FlightPlan.hxx>
50 #include <Navaids/waypoint.hxx>
51 #include <Navaids/fix.hxx>
52 #include <Autopilot/route_mgr.hxx>
53 #include <Navaids/routePath.hxx>
54 #include <Navaids/procedure.hxx>
55 #include <Navaids/airways.hxx>
56 #include <Navaids/NavDataCache.hxx>
57
58 using namespace flightgear;
59
60 static void positionedGhostDestroy(void* g);
61 static void wayptGhostDestroy(void* g);
62 static void legGhostDestroy(void* g);
63 static void routeBaseGhostDestroy(void* g);
64
65 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
66
67 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
68 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
69
70 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
71 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
72
73 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
74 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
75 naGhostType TaxiwayGhostType = { positionedGhostDestroy, "taxiway", runwayGhostGetMember, 0 };
76
77 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
78 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
79
80 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
81 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value);
82
83 naGhostType WayptGhostType = { wayptGhostDestroy, 
84   "waypoint",
85   wayptGhostGetMember,
86   waypointGhostSetMember};
87
88 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
89 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
90
91 naGhostType FPLegGhostType = { legGhostDestroy, 
92   "flightplan-leg",
93   legGhostGetMember,
94   legGhostSetMember};
95
96 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
97 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
98
99 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy, 
100   "flightplan",
101   flightplanGhostGetMember,
102   flightplanGhostSetMember
103 };
104
105 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
106 naGhostType ProcedureGhostType = { routeBaseGhostDestroy, 
107   "procedure",
108   procedureGhostGetMember,
109   0};
110
111 static void hashset(naContext c, naRef hash, const char* key, naRef val)
112 {
113   naRef s = naNewString(c);
114   naStr_fromdata(s, (char*)key, strlen(key));
115   naHash_set(hash, s, val);
116 }
117
118 static naRef stringToNasal(naContext c, const std::string& s)
119 {
120     return naStr_fromdata(naNewString(c),
121                    const_cast<char *>(s.c_str()), 
122                    s.length());
123 }
124
125 static WayptFlag wayptFlagFromString(const char* s)
126 {
127   if (!strcmp(s, "sid")) return WPT_DEPARTURE;
128   if (!strcmp(s, "star")) return WPT_ARRIVAL;
129   if (!strcmp(s, "approach")) return WPT_APPROACH;
130   if (!strcmp(s, "missed")) return WPT_MISS;
131   if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
132   
133   return (WayptFlag) 0;
134 }
135
136 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
137 {
138   if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
139   if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
140   if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
141   if (flags & WPT_MISS) return stringToNasal(c, "missed");
142   if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
143   return naNil();
144 }
145
146 static FGPositioned* positionedGhost(naRef r)
147 {
148     if ((naGhost_type(r) == &AirportGhostType) ||
149         (naGhost_type(r) == &NavaidGhostType) ||
150         (naGhost_type(r) == &RunwayGhostType) ||
151         (naGhost_type(r) == &FixGhostType))
152     {
153         return (FGPositioned*) naGhost_ptr(r);
154     }
155   
156     return 0;
157 }
158
159 static FGAirport* airportGhost(naRef r)
160 {
161   if (naGhost_type(r) == &AirportGhostType)
162     return (FGAirport*) naGhost_ptr(r);
163   return 0;
164 }
165
166 static FGNavRecord* navaidGhost(naRef r)
167 {
168   if (naGhost_type(r) == &NavaidGhostType)
169     return (FGNavRecord*) naGhost_ptr(r);
170   return 0;
171 }
172
173 static FGRunway* runwayGhost(naRef r)
174 {
175   if (naGhost_type(r) == &RunwayGhostType)
176     return (FGRunway*) naGhost_ptr(r);
177   return 0;
178 }
179
180 static FGTaxiway* taxiwayGhost(naRef r)
181 {
182   if (naGhost_type(r) == &TaxiwayGhostType)
183     return (FGTaxiway*) naGhost_ptr(r);
184   return 0;
185 }
186
187 static FGFix* fixGhost(naRef r)
188 {
189   if (naGhost_type(r) == &FixGhostType)
190     return (FGFix*) naGhost_ptr(r);
191   return 0;
192 }
193
194
195 static void positionedGhostDestroy(void* g)
196 {
197     FGPositioned* pos = (FGPositioned*)g;
198     if (!FGPositioned::put(pos)) // unref
199         delete pos;
200 }
201
202 static Waypt* wayptGhost(naRef r)
203 {
204   if (naGhost_type(r) == &WayptGhostType)
205     return (Waypt*) naGhost_ptr(r);
206   
207   if (naGhost_type(r) == &FPLegGhostType) {
208     FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
209     return leg->waypoint();
210   }
211   
212   return 0;
213 }
214
215 static void wayptGhostDestroy(void* g)
216 {
217   Waypt* wpt = (Waypt*)g;
218   if (!Waypt::put(wpt)) // unref
219     delete wpt;
220 }
221
222 static void legGhostDestroy(void* g)
223 {
224   // nothing for now
225 }
226
227
228 static FlightPlan::Leg* fpLegGhost(naRef r)
229 {
230   if (naGhost_type(r) == &FPLegGhostType)
231     return (FlightPlan::Leg*) naGhost_ptr(r);
232   return 0;
233 }
234
235 static Procedure* procedureGhost(naRef r)
236 {
237   if (naGhost_type(r) == &ProcedureGhostType)
238     return (Procedure*) naGhost_ptr(r);
239   return 0;
240 }
241
242 static FlightPlan* flightplanGhost(naRef r)
243 {
244   if (naGhost_type(r) == &FlightPlanGhostType)
245     return (FlightPlan*) naGhost_ptr(r);
246   return 0;
247 }
248
249 static void routeBaseGhostDestroy(void* g)
250 {
251   // nothing for now
252 }
253
254 static naRef airportPrototype;
255 static naRef flightplanPrototype;
256 static naRef waypointPrototype;
257 static naRef geoCoordClass;
258 static naRef fpLegPrototype;
259 static naRef procedurePrototype;
260
261 naRef ghostForAirport(naContext c, const FGAirport* apt)
262 {
263   if (!apt) {
264     return naNil();
265   }
266   
267   FGPositioned::get(apt); // take a ref
268   return naNewGhost2(c, &AirportGhostType, (void*) apt);
269 }
270
271 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
272 {
273   if (!n) {
274     return naNil();
275   }
276   
277   FGPositioned::get(n); // take a ref
278   return naNewGhost2(c, &NavaidGhostType, (void*) n);
279 }
280
281 naRef ghostForRunway(naContext c, const FGRunway* r)
282 {
283   if (!r) {
284     return naNil();
285   }
286   
287   FGPositioned::get(r); // take a ref
288   return naNewGhost2(c, &RunwayGhostType, (void*) r);
289 }
290
291 naRef ghostForTaxiway(naContext c, const FGTaxiway* r)
292 {
293   if (!r) {
294     return naNil();
295   }
296   
297   FGPositioned::get(r); // take a ref
298   return naNewGhost2(c, &TaxiwayGhostType, (void*) r);
299 }
300
301 naRef ghostForFix(naContext c, const FGFix* r)
302 {
303   if (!r) {
304     return naNil();
305   }
306   
307   FGPositioned::get(r); // take a ref
308   return naNewGhost2(c, &FixGhostType, (void*) r);
309 }
310
311
312 naRef ghostForWaypt(naContext c, const Waypt* wpt)
313 {
314   if (!wpt) {
315     return naNil();
316   }
317
318   Waypt::get(wpt); // take a ref
319   return naNewGhost2(c, &WayptGhostType, (void*) wpt);
320 }
321
322 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
323 {
324   if (!leg) {
325     return naNil();
326   }
327   
328   return naNewGhost2(c, &FPLegGhostType, (void*) leg);
329 }
330
331 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
332 {
333   if (!fp) {
334     return naNil();
335   }
336   
337   return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
338 }
339
340 naRef ghostForProcedure(naContext c, const Procedure* proc)
341 {
342   if (!proc) {
343     return naNil();
344   }
345   
346   return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
347 }
348
349 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
350 {
351   const char* fieldName = naStr_data(field);
352   FGAirport* apt = (FGAirport*) g;
353   
354   if (!strcmp(fieldName, "parents")) {
355     *out = naNewVector(c);
356     naVec_append(*out, airportPrototype);
357   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
358   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
359   else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
360   else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
361   else if (!strcmp(fieldName, "elevation")) {
362     *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
363   } else if (!strcmp(fieldName, "has_metar")) {
364     *out = naNum(apt->getMetar());
365   } else if (!strcmp(fieldName, "runways")) {
366     *out = naNewHash(c);
367     double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
368     for(unsigned int r=0; r<apt->numRunways(); ++r) {
369       FGRunway* rwy(apt->getRunwayByIndex(r));
370       
371     // ignore unusably short runways
372       if (rwy->lengthFt() < minLengthFt) {
373         continue;
374       }
375       
376       naRef rwyid = stringToNasal(c, rwy->ident());
377       naRef rwydata = ghostForRunway(c, rwy);
378       naHash_set(*out, rwyid, rwydata);
379     }
380
381   } else if (!strcmp(fieldName, "taxiways")) {
382     *out = naNewVector(c);
383     for(unsigned int r=0; r<apt->numTaxiways(); ++r) {
384       FGTaxiway* taxi(apt->getTaxiwayByIndex(r));
385       naRef taxidata = ghostForTaxiway(c, taxi);
386       naVec_append(*out, taxidata);
387     }
388
389   } else {
390     return 0;
391   }
392   
393   return "";
394 }
395
396 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
397 {
398   if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
399   else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
400   else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
401   else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
402   else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
403   else if (!strcmp(fieldName, "wp_parent_name")) {
404     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
405     *out = proc ? stringToNasal(c, proc->ident()) : naNil();
406   } else if (!strcmp(fieldName, "wp_parent")) {
407     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
408     *out = ghostForProcedure(c, proc);
409   } else if (!strcmp(fieldName, "fly_type")) {
410     if (wpt->type() == "hold") {
411       *out = stringToNasal(c, "Hold");
412     } else {
413       *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
414     }
415   } else {
416     return NULL; // member not found
417   }
418
419   return "";
420 }
421
422 static void waypointCommonSetMember(naContext c, Waypt* wpt, const char* fieldName, naRef value)
423 {
424   if (!strcmp(fieldName, "wp_role")) {
425     if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
426     if (wpt->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
427     WayptFlag f = wayptFlagFromString(naStr_data(value));
428     if (f == 0) {
429       naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
430     }
431     
432     wpt->setFlag(f, true);
433   }
434 }
435
436 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
437 {
438   const char* fieldName = naStr_data(field);
439   Waypt* wpt = (flightgear::Waypt*) g;
440   return waypointCommonGetMember(c, wpt, fieldName, out);
441 }
442
443 static RouteRestriction routeRestrictionFromString(const char* s)
444 {
445   string u(s);
446   boost::to_lower(u);
447   if (u == "computed") return RESTRICT_COMPUTED;
448   if (u == "at") return RESTRICT_AT;
449   if (u == "mach") return SPEED_RESTRICT_MACH;
450   if (u == "computed-mach") return SPEED_COMPUTED_MACH;
451   if (u == "delete") return RESTRICT_DELETE;
452   return RESTRICT_NONE;
453 };
454
455 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
456 {
457   switch (rr) {
458     case RESTRICT_NONE: return naNil();
459     case RESTRICT_AT: return stringToNasal(c, "at");
460     case RESTRICT_ABOVE: return stringToNasal(c, "above");
461     case RESTRICT_BELOW: return stringToNasal(c, "below");
462     case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
463     case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
464     case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
465     case RESTRICT_DELETE: return stringToNasal(c, "delete");
466   }
467   
468   return naNil();
469 }
470
471 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
472 {
473   const char* fieldName = naStr_data(field);
474   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
475   Waypt* wpt = leg->waypoint();
476   
477   if (!strcmp(fieldName, "parents")) {
478     *out = naNewVector(c);
479     naVec_append(*out, fpLegPrototype);
480   } else if (!strcmp(fieldName, "index")) {
481     *out = naNum(leg->index());
482   } else if (!strcmp(fieldName, "alt_cstr")) {
483     *out = naNum(leg->altitudeFt());
484   } else if (!strcmp(fieldName, "alt_cstr_type")) {
485     *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
486   } else if (!strcmp(fieldName, "speed_cstr")) {
487     double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
488     *out = naNum(s);
489   } else if (!strcmp(fieldName, "speed_cstr_type")) {
490     *out = routeRestrictionToNasal(c, leg->speedRestriction());  
491   } else if (!strcmp(fieldName, "leg_distance")) {
492     *out = naNum(leg->distanceNm());
493   } else if (!strcmp(fieldName, "leg_bearing")) {
494     *out = naNum(leg->courseDeg());
495   } else if (!strcmp(fieldName, "distance_along_route")) {
496     *out = naNum(leg->distanceAlongRoute());
497   } else { // check for fields defined on the underlying waypoint
498     return waypointCommonGetMember(c, wpt, fieldName, out);
499   }
500   
501   return ""; // success
502 }
503
504 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
505 {
506   const char* fieldName = naStr_data(field);
507   Waypt* wpt = (Waypt*) g;
508   waypointCommonSetMember(c, wpt, fieldName, value);
509 }
510
511 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
512 {
513   const char* fieldName = naStr_data(field);
514   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
515     
516   waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
517 }
518
519 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
520 {
521   const char* fieldName = naStr_data(field);
522   FlightPlan* fp = (FlightPlan*) g;
523   
524   if (!strcmp(fieldName, "parents")) {
525     *out = naNewVector(c);
526     naVec_append(*out, flightplanPrototype);
527   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
528   else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
529   else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
530   else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
531   else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
532   else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
533   else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
534   else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
535   else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
536   else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
537   else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
538   else {
539     return 0;
540   }
541   
542   return "";
543 }
544
545 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
546 {
547   const char* fieldName = naStr_data(field);
548   FlightPlan* fp = (FlightPlan*) g;
549   
550   if (!strcmp(fieldName, "id")) {
551     if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
552     fp->setIdent(naStr_data(value));
553   } else if (!strcmp(fieldName, "current")) {
554     int index = value.num;
555     if ((index < 0) || (index >= fp->numLegs())) {
556       return;
557     }
558     fp->setCurrentIndex(index);
559   } else if (!strcmp(fieldName, "departure")) {
560     FGAirport* apt = airportGhost(value);
561     if (apt) {
562       fp->setDeparture(apt);
563       return;
564     }
565     
566     FGRunway* rwy = runwayGhost(value);
567     if (rwy){
568       fp->setDeparture(rwy);
569       return;
570     }
571     
572     naRuntimeError(c, "bad argument type setting departure");
573   } else if (!strcmp(fieldName, "destination")) {
574     FGAirport* apt = airportGhost(value);
575     if (apt) {
576       fp->setDestination(apt);
577       return;
578     }
579     
580     FGRunway* rwy = runwayGhost(value);
581     if (rwy){
582       fp->setDestination(rwy);
583       return;
584     }
585     
586     naRuntimeError(c, "bad argument type setting destination");
587   } else if (!strcmp(fieldName, "departure_runway")) {
588     FGRunway* rwy = runwayGhost(value);
589     if (rwy){
590       fp->setDeparture(rwy);
591       return;
592     }
593     
594     naRuntimeError(c, "bad argument type setting departure");
595   } else if (!strcmp(fieldName, "destination_runway")) {
596     FGRunway* rwy = runwayGhost(value);
597     if (rwy){
598       fp->setDestination(rwy);
599       return;
600     }
601     
602     naRuntimeError(c, "bad argument type setting departure");
603   } else if (!strcmp(fieldName, "sid")) {
604     Procedure* proc = procedureGhost(value);
605     if (proc && (proc->type() == PROCEDURE_SID)) {
606       fp->setSID((flightgear::SID*) proc);
607       return;
608     }
609     // allow a SID transition to be set, implicitly include the SID itself
610     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
611       fp->setSID((Transition*) proc);
612       return;
613     }
614         
615     if (naIsString(value)) {
616       FGAirport* apt = fp->departureAirport();
617       fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
618       return;
619     }
620     
621     naRuntimeError(c, "bad argument type setting SID");
622   } else if (!strcmp(fieldName, "star")) {
623     Procedure* proc = procedureGhost(value);
624     if (proc && (proc->type() == PROCEDURE_STAR)) {
625       fp->setSTAR((STAR*) proc);
626       return;
627     }
628     
629     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
630       fp->setSTAR((Transition*) proc);
631       return;
632     }
633     
634     if (naIsString(value)) {
635       FGAirport* apt = fp->destinationAirport();
636       fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
637       return;
638     }
639     
640     naRuntimeError(c, "bad argument type setting STAR");
641   } else if (!strcmp(fieldName, "approach")) {
642     Procedure* proc = procedureGhost(value);
643     if (proc && Approach::isApproach(proc->type())) {
644       fp->setApproach((Approach*) proc);
645       return;
646     }
647     
648     if (naIsString(value)) {
649       FGAirport* apt = fp->destinationAirport();
650       fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
651       return;
652     }
653     
654     naRuntimeError(c, "bad argument type setting approach");
655   }
656 }
657
658
659 static naRef procedureTpType(naContext c, ProcedureType ty)
660 {
661   switch (ty) {
662     case PROCEDURE_SID: return stringToNasal(c, "sid");
663     case PROCEDURE_STAR: return stringToNasal(c, "star");
664     case PROCEDURE_APPROACH_VOR: 
665     case PROCEDURE_APPROACH_ILS: 
666     case PROCEDURE_APPROACH_RNAV: 
667     case PROCEDURE_APPROACH_NDB:
668       return stringToNasal(c, "IAP");
669     default:
670       return naNil();
671   }
672 }
673
674 static naRef procedureRadioType(naContext c, ProcedureType ty)
675 {
676   switch (ty) {
677     case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
678     case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
679     case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
680     case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
681     default:
682       return naNil();
683   }
684 }
685
686 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
687 {
688   const char* fieldName = naStr_data(field);
689   Procedure* proc = (Procedure*) g;
690   
691   if (!strcmp(fieldName, "parents")) {
692     *out = naNewVector(c);
693     naVec_append(*out, procedurePrototype);
694   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
695   else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
696   else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
697   else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
698   else if (!strcmp(fieldName, "runways")) {
699     *out = naNewVector(c);
700     BOOST_FOREACH(FGRunwayRef rwy, proc->runways()) {
701       naVec_append(*out, stringToNasal(c, rwy->ident()));
702     }
703   } else if (!strcmp(fieldName, "transitions")) {
704     if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
705       *out = naNil();
706       return "";
707     }
708         
709     ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
710     *out = naNewVector(c);
711     BOOST_FOREACH(string id, ad->transitionIdents()) {
712       naVec_append(*out, stringToNasal(c, id));
713     }
714   } else {
715     return 0;
716   }
717   
718   return "";
719 }
720
721 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
722 {
723   const char* fieldName = naStr_data(field);
724   FGRunwayBase* base = (FGRunwayBase*) g;
725   
726   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, base->ident());
727   else if (!strcmp(fieldName, "lat")) *out = naNum(base->latitude());
728   else if (!strcmp(fieldName, "lon")) *out = naNum(base->longitude());
729   else if (!strcmp(fieldName, "heading")) *out = naNum(base->headingDeg());
730   else if (!strcmp(fieldName, "length")) *out = naNum(base->lengthM());
731   else if (!strcmp(fieldName, "width")) *out = naNum(base->widthM());
732   else if (!strcmp(fieldName, "surface")) *out = naNum(base->surface());
733   else if (base->type() == FGRunwayBase::RUNWAY) {  
734     FGRunway* rwy = (FGRunway*) g;
735     if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
736     else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
737     else if (!strcmp(fieldName, "ils_frequency_mhz")) {
738       *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
739     } else if (!strcmp(fieldName, "ils")) {
740       *out = ghostForNavaid(c, rwy->ILS());
741     } else {
742       return 0;
743     }
744   } else {
745     return 0;    
746   }
747   
748   return "";
749 }
750
751 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
752 {
753   const char* fieldName = naStr_data(field);
754   FGNavRecord* nav = (FGNavRecord*) g;
755   
756   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
757   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
758   else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
759   else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
760   else if (!strcmp(fieldName, "elevation")) {
761     *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
762   } else if (!strcmp(fieldName, "type")) {
763     *out = stringToNasal(c, nav->nameForType(nav->type()));
764   } else if (!strcmp(fieldName, "frequency")) {
765     *out = naNum(nav->get_freq()); 
766   } else if (!strcmp(fieldName, "range_nm")) {
767     *out = naNum(nav->get_range()); 
768   } else if (!strcmp(fieldName, "course")) {
769     if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
770       double radial = nav->get_multiuse();
771       SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
772       *out = naNum(radial);
773     } else {
774       *out = naNil();
775     }
776   } else {
777     return 0;
778   }
779   
780   return "";
781 }
782
783 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
784 {
785   const char* fieldName = naStr_data(field);
786   FGFix* fix = (FGFix*) g;
787   
788   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
789   else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
790   else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
791   else {
792     return 0;
793   }
794   
795   return "";
796 }
797
798 static bool hashIsCoord(naRef h)
799 {
800   naRef parents = naHash_cget(h, (char*) "parents");
801   if (!naIsVector(parents)) {
802     return false;
803   }
804   
805   return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
806 }
807
808 bool geodFromHash(naRef ref, SGGeod& result)
809 {
810   if (!naIsHash(ref)) {
811     return false;
812   }
813
814   
815 // check for manual latitude / longitude names
816   naRef lat = naHash_cget(ref, (char*) "lat");
817   naRef lon = naHash_cget(ref, (char*) "lon");
818   if (naIsNum(lat) && naIsNum(lon)) {
819     result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
820     return true;
821   }
822   
823   if (hashIsCoord(ref)) {
824     naRef lat = naHash_cget(ref, (char*) "_lat");
825     naRef lon = naHash_cget(ref, (char*) "_lon");
826     if (naIsNum(lat) && naIsNum(lon)) {
827       result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
828       return true;
829     }
830   }
831     
832 // check for any synonyms?
833     // latitude + longitude?
834   
835   return false;
836 }
837
838 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
839 {
840   if (offset >= argc) {
841     return 0;
842   }
843   
844   if (naIsGhost(args[offset])) {
845     naGhostType* gt = naGhost_type(args[offset]);
846     if (gt == &AirportGhostType) {
847       result = airportGhost(args[offset])->geod();
848       return 1;
849     }
850     
851     if (gt == &NavaidGhostType) {
852       result = navaidGhost(args[offset])->geod();
853       return 1;
854     }
855     
856     if (gt == &RunwayGhostType) {
857       result = runwayGhost(args[offset])->geod();
858       return 1;
859     }
860     
861     if (gt == &TaxiwayGhostType) {
862       result = taxiwayGhost(args[offset])->geod();
863       return 1;
864     }
865     
866     if (gt == &FixGhostType) {
867       result = fixGhost(args[offset])->geod();
868       return 1;
869     }
870     
871     if (gt == &WayptGhostType) {
872       result = wayptGhost(args[offset])->position();
873       return 1;
874     }
875   }
876   
877   if (geodFromHash(args[offset], result)) {
878     return 1;
879   }
880   
881   if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
882     double lat = naNumValue(args[0]).num,
883     lon = naNumValue(args[1]).num;
884     result = SGGeod::fromDeg(lon, lat);
885     return 2;
886   }
887   
888   return 0;
889 }
890
891 // Convert a cartesian point to a geodetic lat/lon/altitude.
892 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
893 {
894   double lat, lon, alt, xyz[3];
895   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
896   for(int i=0; i<3; i++)
897     xyz[i] = naNumValue(args[i]).num;
898   sgCartToGeod(xyz, &lat, &lon, &alt);
899   lat *= SG_RADIANS_TO_DEGREES;
900   lon *= SG_RADIANS_TO_DEGREES;
901   naRef vec = naNewVector(c);
902   naVec_append(vec, naNum(lat));
903   naVec_append(vec, naNum(lon));
904   naVec_append(vec, naNum(alt));
905   return vec;
906 }
907
908 // Convert a geodetic lat/lon/altitude to a cartesian point.
909 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
910 {
911   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
912   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
913   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
914   double alt = naNumValue(args[2]).num;
915   double xyz[3];
916   sgGeodToCart(lat, lon, alt, xyz);
917   naRef vec = naNewVector(c);
918   naVec_append(vec, naNum(xyz[0]));
919   naVec_append(vec, naNum(xyz[1]));
920   naVec_append(vec, naNum(xyz[2]));
921   return vec;
922 }
923
924 // For given geodetic point return array with elevation, and a material data
925 // hash, or nil if there's no information available (tile not loaded). If
926 // information about the material isn't available, then nil is returned instead
927 // of the hash.
928 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
929 {
930 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
931   if(argc < 2 || argc > 3)
932     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
933   double lat = naNumValue(args[0]).num;
934   double lon = naNumValue(args[1]).num;
935   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
936   const simgear::BVHMaterial *material;
937   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
938   if(!globals->get_scenery()->get_elevation_m(geod, elev, &material))
939     return naNil();
940   const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
941   naRef vec = naNewVector(c);
942   naVec_append(vec, naNum(elev));
943   naRef matdata = naNil();
944   if(mat) {
945     matdata = naNewHash(c);
946     naRef names = naNewVector(c);
947     BOOST_FOREACH(const std::string& n, mat->get_names())
948       naVec_append(names, stringToNasal(c, n));
949       
950     HASHSET("names", 5, names);
951     HASHSET("solid", 5, naNum(mat->get_solid()));
952     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
953     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
954     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
955     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
956     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
957   }
958   naVec_append(vec, matdata);
959   return vec;
960 #undef HASHSET
961 }
962
963
964 class AirportInfoFilter : public FGAirport::AirportFilter
965 {
966 public:
967   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
968     minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
969   }
970   
971   bool fromArg(naRef arg)
972   {
973     const char *s = naStr_data(arg);
974     if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
975     else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
976     else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
977     else
978       return false;
979     
980     return true;
981   }
982   
983   virtual FGPositioned::Type minType() const {
984     return type;
985   }
986   
987   virtual FGPositioned::Type maxType() const {
988     return type;
989   }
990     
991   virtual bool pass(FGPositioned* aPos) const
992   {
993     FGAirport* apt = (FGAirport*) aPos;
994     if ((apt->type() == FGPositioned::AIRPORT) && 
995         !apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) 
996     {
997       return false;
998     }
999
1000     return true;
1001   }
1002   
1003   FGPositioned::Type type;
1004   double minRunwayLengthFt;
1005 };
1006
1007 // Returns data hash for particular or nearest airport of a <type>, or nil
1008 // on error.
1009 //
1010 // airportinfo(<id>);                   e.g. "KSFO"
1011 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
1012 // airportinfo()                        same as  airportinfo("airport")
1013 // airportinfo(<lat>, <lon> [, <type>]);
1014 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
1015 {
1016   SGGeod pos = globals->get_aircraft_position();
1017   FGAirport* apt = NULL;
1018   
1019   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1020     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1021     args += 2;
1022     argc -= 2;
1023   }
1024   
1025   double maxRange = 10000.0; // expose this? or pick a smaller value?
1026   
1027   AirportInfoFilter filter; // defaults to airports only
1028   
1029   if(argc == 0) {
1030     // fall through and use AIRPORT
1031   } else if(argc == 1 && naIsString(args[0])) {
1032     if (filter.fromArg(args[0])) {
1033       // done!
1034     } else {
1035       // user provided an <id>, hopefully
1036       apt = FGAirport::findByIdent(naStr_data(args[0]));
1037       if (!apt) {
1038         // return nil here, but don't raise a runtime error; this is a
1039         // legitamate way to validate an ICAO code, for example in a
1040         // dialog box or similar.
1041         return naNil();
1042       }
1043     }
1044   } else {
1045     naRuntimeError(c, "airportinfo() with invalid function arguments");
1046     return naNil();
1047   }
1048   
1049   if(!apt) {
1050     apt = FGAirport::findClosest(pos, maxRange, &filter);
1051     if(!apt) return naNil();
1052   }
1053   
1054   return ghostForAirport(c, apt);
1055 }
1056
1057 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1058 {
1059   int argOffset = 0;
1060   SGGeod pos = globals->get_aircraft_position();
1061   argOffset += geodFromArgs(args, 0, argc, pos);
1062   
1063   if (!naIsNum(args[argOffset])) {
1064     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1065   }
1066   
1067   AirportInfoFilter filter; // defaults to airports only
1068   double rangeNm = args[argOffset++].num;
1069   if (argOffset < argc) {
1070     filter.fromArg(args[argOffset++]);
1071   }
1072   
1073   naRef r = naNewVector(c);
1074   
1075   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1076   FGPositioned::sortByRange(apts, pos);
1077   
1078   BOOST_FOREACH(FGPositionedRef a, apts) {
1079     FGAirport* apt = (FGAirport*) a.get();
1080     naVec_append(r, ghostForAirport(c, apt));
1081   }
1082   
1083   return r;
1084 }
1085
1086 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1087 {
1088   if (!naIsString(args[0])) {
1089     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1090   }
1091   
1092   int argOffset = 0;
1093   string prefix(naStr_data(args[argOffset++]));
1094   AirportInfoFilter filter; // defaults to airports only
1095   if (argOffset < argc) {
1096     filter.fromArg(args[argOffset++]);
1097   }
1098   
1099   naRef r = naNewVector(c);
1100   
1101   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1102   
1103   BOOST_FOREACH(FGPositionedRef a, apts) {
1104     FGAirport* apt = (FGAirport*) a.get();
1105     naVec_append(r, ghostForAirport(c, apt));
1106   }
1107   
1108   return r;
1109 }
1110
1111 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1112 {
1113     FGAirport* apt = airportGhost(me);
1114     if (!apt) {
1115       naRuntimeError(c, "airport.tower called on non-airport object");
1116     }
1117   
1118     // build a hash for the tower position    
1119     SGGeod towerLoc = apt->getTowerLocation();
1120     naRef tower = naNewHash(c);
1121     hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1122     hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1123     hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1124     return tower;
1125 }
1126
1127 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1128 {
1129     FGAirport* apt = airportGhost(me);
1130     if (!apt) {
1131       naRuntimeError(c, "airport.comms called on non-airport object");
1132     }
1133     naRef comms = naNewVector(c);
1134     
1135 // if we have an explicit type, return a simple vector of frequencies
1136     if (argc > 0 && naIsScalar(args[0])) {
1137         std::string commName = naStr_data(args[0]);
1138         FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1139         
1140         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1141             naVec_append(comms, naNum(comm->freqMHz()));
1142         }
1143     } else {
1144 // otherwise return a vector of hashes, one for each comm station.
1145         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1146             naRef commHash = naNewHash(c);
1147             hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1148             hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1149             naVec_append(comms, commHash);
1150         }
1151     }
1152     
1153     return comms;
1154 }
1155
1156 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1157 {
1158   FGAirport* apt = airportGhost(me);
1159   if (!apt) {
1160     naRuntimeError(c, "airport.runway called on non-airport object");
1161   }
1162   
1163   if ((argc < 1) || !naIsString(args[0])) {
1164     naRuntimeError(c, "airport.runway expects a runway ident argument");
1165   }
1166   
1167   std::string ident(naStr_data(args[0]));
1168   boost::to_upper(ident);
1169   if (!apt->hasRunwayWithIdent(ident)) {
1170     return naNil();
1171   }
1172   
1173   return ghostForRunway(c, apt->getRunwayByIdent(ident));
1174 }
1175
1176 static naRef f_airport_taxiway(naContext c, naRef me, int argc, naRef* args)
1177 {
1178   FGAirport* apt = airportGhost(me);
1179   if (!apt) {
1180     naRuntimeError(c, "airport.taxiway called on non-airport object");
1181   }
1182   
1183   if ((argc < 1) || !naIsString(args[0])) {
1184     naRuntimeError(c, "airport.taxiway expects a taxiway ident argument");
1185   }
1186   
1187   naRef taxiways = naNewVector(c);
1188   
1189   for (unsigned int i = 0; i < apt->numTaxiways(); i++) {
1190     naVec_append(taxiways, ghostForTaxiway(c, apt->getTaxiwayByIndex(i)));
1191   }
1192   
1193   return taxiways;  
1194 }
1195
1196 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1197 {
1198   FGAirport* apt = airportGhost(me);
1199   if (!apt) {
1200     naRuntimeError(c, "airport.sids called on non-airport object");
1201   }
1202   
1203   naRef sids = naNewVector(c);
1204   
1205   FGRunway* rwy = NULL;
1206   if (argc > 0 && naIsString(args[0])) {
1207     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1208       return naNil();
1209     }
1210
1211     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1212   } else if (argc > 0) {
1213     rwy = runwayGhost(args[0]);
1214   }
1215
1216   if (rwy) {
1217     BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1218       naRef procId = stringToNasal(c, sid->ident());
1219       naVec_append(sids, procId);
1220     }
1221   } else {
1222     for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1223       flightgear::SID* sid = apt->getSIDByIndex(s);
1224       naRef procId = stringToNasal(c, sid->ident());
1225       naVec_append(sids, procId);
1226     }
1227   }
1228   
1229   return sids;
1230 }
1231
1232 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1233 {
1234   FGAirport* apt = airportGhost(me);
1235   if (!apt) {
1236     naRuntimeError(c, "airport.stars called on non-airport object");
1237   }
1238   
1239   naRef stars = naNewVector(c);
1240   
1241   FGRunway* rwy = NULL;
1242   if (argc > 0 && naIsString(args[0])) {
1243     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1244       return naNil();
1245     }
1246         
1247     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1248   } else if (argc > 0) {
1249     rwy = runwayGhost(args[0]);
1250   }
1251   
1252   if (rwy) {
1253     BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1254       naRef procId = stringToNasal(c, s->ident());
1255       naVec_append(stars, procId);
1256     }
1257   } else {
1258     for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1259       flightgear::STAR* star = apt->getSTARByIndex(s);
1260       naRef procId = stringToNasal(c, star->ident());
1261       naVec_append(stars, procId);
1262     }
1263   }
1264   
1265   return stars;
1266 }
1267
1268 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1269 {
1270   FGAirport* apt = airportGhost(me);
1271   if (!apt) {
1272     naRuntimeError(c, "airport.getApproachList called on non-airport object");
1273   }
1274   
1275   naRef approaches = naNewVector(c);
1276   
1277   ProcedureType ty = PROCEDURE_INVALID;
1278   if ((argc > 1) && naIsString(args[1])) {
1279     std::string u(naStr_data(args[1]));
1280     boost::to_upper(u);
1281     if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1282     if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1283     if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1284     if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1285   }
1286   
1287   FGRunway* rwy = NULL;
1288   if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1289     // ok
1290   } else if (argc > 0 && naIsString(args[0])) {
1291     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1292       return naNil();
1293     }
1294     
1295     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1296   }
1297   
1298   if (rwy) {
1299     BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1300       if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1301         continue;
1302       }
1303       
1304       naRef procId = stringToNasal(c, s->ident());
1305       naVec_append(approaches, procId);
1306     }
1307   } else {
1308     // no runway specified, report them all
1309     for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1310       Approach* app = apt->getApproachByIndex(s);
1311       if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1312         continue;
1313       }
1314       
1315       naRef procId = stringToNasal(c, app->ident());
1316       naVec_append(approaches, procId);
1317     }
1318   }
1319   
1320   return approaches;
1321 }
1322
1323 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1324 {
1325   FGAirport* apt = airportGhost(me);
1326   if (!apt) {
1327     naRuntimeError(c, "airport.parking called on non-airport object");
1328   }
1329   
1330   naRef r = naNewVector(c);
1331   std::string type;
1332   bool onlyAvailable = false;
1333   
1334   if (argc > 0 && naIsString(args[0])) {
1335     type = naStr_data(args[0]);
1336   }
1337   
1338   if ((argc > 1) && naIsNum(args[1])) {
1339     onlyAvailable = (args[1].num != 0.0);
1340   }
1341   
1342   FGAirportDynamics* dynamics = apt->getDynamics();
1343   PositionedIDVec parkings = flightgear::NavDataCache::instance()->airportItemsOfType(apt->guid(),
1344                                                                                       FGPositioned::PARKING);
1345   
1346   BOOST_FOREACH(PositionedID parking, parkings) {
1347     // filter out based on availability and type
1348     if (onlyAvailable && !dynamics->isParkingAvailable(parking)) {
1349       continue;
1350     }
1351     
1352     FGParking* park = dynamics->getParking(parking);
1353     if (!type.empty() && (park->getType() != type)) {
1354       continue;
1355     }
1356     
1357     const SGGeod& parkLoc = park->geod();
1358     naRef ph = naNewHash(c);
1359     hashset(c, ph, "name", stringToNasal(c, park->getName()));
1360     hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1361     hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1362     hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1363     naVec_append(r, ph);
1364   }
1365   
1366   return r;
1367 }
1368
1369 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1370 {
1371   FGAirport* apt = airportGhost(me);
1372   if (!apt) {
1373     naRuntimeError(c, "airport.getSid called on non-airport object");
1374   }
1375   
1376   if ((argc != 1) || !naIsString(args[0])) {
1377     naRuntimeError(c, "airport.getSid passed invalid argument");
1378   }
1379   
1380   string ident = naStr_data(args[0]);
1381   return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1382 }
1383
1384 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1385 {
1386   FGAirport* apt = airportGhost(me);
1387   if (!apt) {
1388     naRuntimeError(c, "airport.getStar called on non-airport object");
1389   }
1390   
1391   if ((argc != 1) || !naIsString(args[0])) {
1392     naRuntimeError(c, "airport.getStar passed invalid argument");
1393   }
1394   
1395   string ident = naStr_data(args[0]);
1396   return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1397 }
1398
1399 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1400 {
1401   FGAirport* apt = airportGhost(me);
1402   if (!apt) {
1403     naRuntimeError(c, "airport.getIAP called on non-airport object");
1404   }
1405   
1406   if ((argc != 1) || !naIsString(args[0])) {
1407     naRuntimeError(c, "airport.getIAP passed invalid argument");
1408   }
1409   
1410   string ident = naStr_data(args[0]);
1411   return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1412 }
1413
1414 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1415 {
1416   FGAirport* apt = airportGhost(me);
1417   if (!apt) {
1418     naRuntimeError(c, "airport.tostring called on non-airport object");
1419   }
1420   
1421   return stringToNasal(c, "an airport " + apt->ident());
1422 }
1423
1424 // Returns vector of data hash for navaid of a <type>, nil on error
1425 // navaids sorted by ascending distance 
1426 // navinfo([<lat>,<lon>],[<type>],[<id>])
1427 // lat/lon (numeric): use latitude/longitude instead of ac position
1428 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1429 // id:                (partial) id of the fix
1430 // examples:
1431 // navinfo("vor")     returns all vors
1432 // navinfo("HAM")     return all navaids who's name start with "HAM"
1433 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1434 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
1435 //                           sorted by distance relative to lat=34, lon=48
1436 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1437 {
1438   SGGeod pos;
1439   
1440   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1441     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1442     args += 2;
1443     argc -= 2;
1444   } else {
1445     pos = globals->get_aircraft_position();
1446   }
1447   
1448   FGPositioned::Type type = FGPositioned::INVALID;
1449   nav_list_type navlist;
1450   const char * id = "";
1451   
1452   if(argc > 0 && naIsString(args[0])) {
1453     const char *s = naStr_data(args[0]);
1454     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1455     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1456     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1457     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1458     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1459     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1460     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1461     else id = s; // this is an id
1462     ++args;
1463     --argc;
1464   } 
1465   
1466   if(argc > 0 && naIsString(args[0])) {
1467     if( *id != 0 ) {
1468       naRuntimeError(c, "navinfo() called with navaid id");
1469       return naNil();
1470     }
1471     id = naStr_data(args[0]);
1472     ++args;
1473     --argc;
1474   }
1475   
1476   if( argc > 0 ) {
1477     naRuntimeError(c, "navinfo() called with too many arguments");
1478     return naNil();
1479   }
1480   
1481   FGNavList::TypeFilter filter(type);
1482   navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1483   
1484   naRef reply = naNewVector(c);
1485   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1486     naVec_append( reply, ghostForNavaid(c, *it) );
1487   }
1488   return reply;
1489 }
1490
1491 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1492 {
1493   int argOffset = 0;
1494   SGGeod pos = globals->get_aircraft_position();
1495   argOffset += geodFromArgs(args, 0, argc, pos);
1496   
1497   if (!naIsNum(args[argOffset])) {
1498     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1499   }
1500   
1501   FGPositioned::Type type = FGPositioned::INVALID;
1502   double rangeNm = args[argOffset++].num;
1503   if (argOffset < argc) {
1504     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1505   }
1506   
1507   naRef r = naNewVector(c);
1508   FGNavList::TypeFilter filter(type);
1509   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1510   FGPositioned::sortByRange(navs, pos);
1511   
1512   BOOST_FOREACH(FGPositionedRef a, navs) {
1513     FGNavRecord* nav = (FGNavRecord*) a.get();
1514     naVec_append(r, ghostForNavaid(c, nav));
1515   }
1516   
1517   return r;
1518 }
1519
1520 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1521 {
1522   int argOffset = 0;
1523   SGGeod pos = globals->get_aircraft_position();
1524   argOffset += geodFromArgs(args, 0, argc, pos);
1525   
1526   if (!naIsNum(args[argOffset])) {
1527     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1528   }
1529   
1530   FGPositioned::Type type = FGPositioned::INVALID;
1531   double freqMhz = args[argOffset++].num;
1532   if (argOffset < argc) {
1533     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1534   }
1535   
1536   FGNavList::TypeFilter filter(type);
1537   nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1538   if (navs.empty()) {
1539     return naNil();
1540   }
1541   
1542   return ghostForNavaid(c, navs.front().ptr());
1543 }
1544
1545 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1546 {
1547   int argOffset = 0;
1548   SGGeod pos = globals->get_aircraft_position();
1549   argOffset += geodFromArgs(args, 0, argc, pos);
1550   
1551   if (!naIsNum(args[argOffset])) {
1552     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1553   }
1554   
1555   FGPositioned::Type type = FGPositioned::INVALID;
1556   double freqMhz = args[argOffset++].num;
1557   if (argOffset < argc) {
1558     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1559   }
1560   
1561   naRef r = naNewVector(c);
1562   
1563   FGNavList::TypeFilter filter(type);
1564   nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1565   
1566   BOOST_FOREACH(nav_rec_ptr a, navs) {
1567     naVec_append(r, ghostForNavaid(c, a.ptr()));
1568   }
1569   
1570   return r;
1571 }
1572
1573 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1574 {
1575   int argOffset = 0;
1576   SGGeod pos = globals->get_aircraft_position();
1577   argOffset += geodFromArgs(args, 0, argc, pos);
1578   
1579   if (!naIsString(args[argOffset])) {
1580     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1581   }
1582   
1583   FGPositioned::Type type = FGPositioned::INVALID;
1584   string ident = naStr_data(args[argOffset++]);
1585   if (argOffset < argc) {
1586     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1587   }
1588   
1589   FGNavList::TypeFilter filter(type);
1590   naRef r = naNewVector(c);
1591   nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1592   
1593   BOOST_FOREACH(nav_rec_ptr a, navs) {
1594     naVec_append(r, ghostForNavaid(c, a.ptr()));
1595   }
1596   
1597   return r;
1598 }
1599
1600 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1601 {
1602   int argOffset = 0;
1603   SGGeod pos = globals->get_aircraft_position();
1604   argOffset += geodFromArgs(args, 0, argc, pos);
1605   
1606   if (!naIsString(args[argOffset])) {
1607     naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1608   }
1609   
1610   string ident(naStr_data(args[argOffset]));
1611   naRef r = naNewVector(c);
1612   
1613   FGPositioned::TypeFilter filter(FGPositioned::FIX);
1614   FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1615   FGPositioned::sortByRange(fixes, pos);
1616   
1617   BOOST_FOREACH(FGPositionedRef f, fixes) {
1618     naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1619   }
1620   
1621   return r;
1622 }
1623
1624 // Convert a cartesian point to a geodetic lat/lon/altitude.
1625 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1626 {
1627   SGGeod pos = globals->get_aircraft_position();
1628   if (argc == 0) {
1629     // fine, use aircraft position
1630   } else if (geodFromArgs(args, 0, argc, pos)) {
1631     // okay
1632   } else {
1633     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1634   }
1635   
1636   double jd = globals->get_time_params()->getJD();
1637   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1638   return naNum(magvarDeg);
1639 }
1640
1641 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1642 {
1643     SGGeod from = globals->get_aircraft_position(), to, p;
1644     int argOffset = geodFromArgs(args, 0, argc, p);
1645     if (geodFromArgs(args, argOffset, argc, to)) {
1646       from = p; // we parsed both FROM and TO args, so first was from
1647     } else {
1648       to = p; // only parsed one arg, so FROM is current
1649     }
1650   
1651     if (argOffset == 0) {
1652         naRuntimeError(c, "invalid arguments to courseAndDistance");
1653     }
1654     
1655     double course, course2, d;
1656     SGGeodesy::inverse(from, to, course, course2, d);
1657     
1658     naRef result = naNewVector(c);
1659     naVec_append(result, naNum(course));
1660     naVec_append(result, naNum(d * SG_METER_TO_NM));
1661     return result;
1662 }
1663
1664 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1665 {
1666   SGGeod from = globals->get_aircraft_position(), to;
1667   int argOffset = 0;
1668   
1669   // complication - don't inerpret two doubles (as the only args)
1670   // as a lat,lon pair - only do so if we have at least three args.
1671   if (argc > 2) {
1672     argOffset = geodFromArgs(args, 0, argc, from);
1673   }
1674   
1675   if ((argOffset + 1) >= argc) {
1676     naRuntimeError(c, "isufficent arguments to greatCircleMove");
1677   }
1678   
1679   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1680     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1681                    argOffset, argOffset + 1);
1682   }
1683   
1684   double course = args[argOffset].num, course2;
1685   double distanceNm = args[argOffset + 1].num;
1686   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1687   
1688   // return geo.Coord
1689   naRef coord = naNewHash(c);
1690   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1691   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1692   return coord;
1693 }
1694
1695 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1696 {
1697     SGGeod pos = globals->get_aircraft_position();
1698     geodFromArgs(args, 0, argc, pos);
1699     SGBucket b(pos);
1700     return stringToNasal(c, b.gen_base_path());
1701 }
1702
1703 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1704 {
1705   SGGeod pos = globals->get_aircraft_position();
1706   geodFromArgs(args, 0, argc, pos);
1707   SGBucket b(pos);
1708   return naNum(b.gen_index());
1709 }
1710
1711 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1712 {
1713   if (argc == 0) {
1714     FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));  
1715     return ghostForFlightPlan(c, rm->flightPlan());
1716   }
1717   
1718   if ((argc > 0) && naIsString(args[0])) {
1719     flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1720     SGPath path(naStr_data(args[0]));
1721     if (!path.exists()) {
1722       naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1723     }
1724     
1725     if (!fp->load(path)) {
1726       SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1727       delete fp;
1728       return naNil();
1729     }
1730     
1731     return ghostForFlightPlan(c, fp);
1732   }
1733   
1734   naRuntimeError(c, "bad arguments to flightplan()");
1735   return naNil();
1736 }
1737
1738 class NasalFPDelegate : public FlightPlan::Delegate
1739 {
1740 public:
1741   NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1742     _nasal(sys),
1743     _plan(fp),
1744     _instance(ins)
1745   {
1746     SG_LOG(SG_NASAL, SG_INFO, "created Nasal delegate for " << fp);
1747     _gcSaveKey = _nasal->gcSave(ins);
1748   }
1749   
1750   virtual ~NasalFPDelegate()
1751   {
1752     SG_LOG(SG_NASAL, SG_INFO, "destroying Nasal delegate for " << _plan);
1753     _nasal->gcRelease(_gcSaveKey);
1754   }
1755   
1756   virtual void departureChanged()
1757   {
1758     callDelegateMethod("departureChanged");
1759   }
1760   
1761   virtual void arrivalChanged()
1762   {
1763     callDelegateMethod("arrivalChanged");
1764   }
1765   
1766   virtual void waypointsChanged()
1767   {
1768     callDelegateMethod("waypointsChanged");
1769   }
1770   
1771   virtual void currentWaypointChanged()
1772   {
1773     callDelegateMethod("currentWaypointChanged");
1774   }
1775 private:
1776   
1777   void callDelegateMethod(const char* method)
1778   {
1779     naRef f;
1780     naMember_cget(_nasal->context(), _instance, method, &f);
1781     if (naIsNil(f)) {
1782       return; // no method on the delegate
1783     }
1784     
1785     naRef arg[1];
1786     arg[0] = ghostForFlightPlan(_nasal->context(), _plan);
1787     _nasal->callMethod(f, _instance, 1, arg, naNil());
1788   }
1789   
1790   FGNasalSys* _nasal;
1791   FlightPlan* _plan;
1792   naRef _instance;
1793   int _gcSaveKey;
1794 };
1795
1796 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1797 {
1798 public:
1799   NasalFPDelegateFactory(naRef code)
1800   {
1801     _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1802     _func = code;
1803     _gcSaveKey = _nasal->gcSave(_func);
1804   }
1805   
1806   ~NasalFPDelegateFactory()
1807   {
1808     _nasal->gcRelease(_gcSaveKey);
1809   }
1810   
1811   virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1812   {
1813     naRef args[1];
1814     args[0] = ghostForFlightPlan(_nasal->context(), fp);
1815     naRef instance = _nasal->call(_func, 1, args, naNil());
1816     if (naIsNil(instance)) {
1817       return NULL;
1818     }
1819     
1820     return new NasalFPDelegate(fp, _nasal, instance);
1821   }
1822 private:
1823   FGNasalSys* _nasal;
1824   naRef _func;
1825   int _gcSaveKey;
1826 };
1827
1828 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1829 {
1830   if ((argc < 1) || !naIsFunc(args[0])) {
1831     naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1832   }
1833   
1834   NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1835   FlightPlan::registerDelegateFactory(factory);
1836   
1837   return naNil();
1838 }
1839
1840 static WayptRef wayptFromArg(naRef arg)
1841 {
1842   WayptRef r = wayptGhost(arg);
1843   if (r.valid()) {
1844     return r;
1845   }
1846   
1847   FGPositioned* pos = positionedGhost(arg);
1848   if (!pos) {
1849     // let's check if the arg is hash, coudl extra a geod and hence build
1850     // a simple waypoint
1851     
1852     return WayptRef();
1853   }
1854   
1855 // special-case for runways
1856   if (pos->type() == FGPositioned::RUNWAY) {
1857     return new RunwayWaypt((FGRunway*) pos, NULL);
1858   }
1859   
1860   return new NavaidWaypoint(pos, NULL);
1861 }
1862
1863 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1864 {
1865   naRef result = naNewVector(c);
1866   BOOST_FOREACH(WayptRef wpt, wps) {
1867     naVec_append(result, ghostForWaypt(c, wpt.get()));
1868   }
1869   return result;
1870 }
1871
1872 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1873 {
1874   if (argc < 2) {
1875     naRuntimeError(c, "airwaysSearch needs at least two arguments");
1876   }
1877   
1878   WayptRef start = wayptFromArg(args[0]), 
1879     end = wayptFromArg(args[1]);
1880   
1881   if (!start || !end) {
1882     SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1883     return naNil();
1884   }
1885   
1886   bool highLevel = true;
1887   if ((argc > 2) && naIsString(args[2])) {
1888     if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1889       highLevel = false;
1890     }
1891   }
1892   
1893   WayptVec route;
1894   if (highLevel) {
1895     Airway::highLevel()->route(start, end, route);
1896   } else {
1897     Airway::lowLevel()->route(start, end, route);
1898   }
1899   
1900   return convertWayptVecToNasal(c, route);
1901 }
1902
1903 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1904 {
1905   SGGeod pos;
1906   int argOffset = geodFromArgs(args, 0, argc, pos);
1907   
1908   if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1909     naRuntimeError(c, "createWP: no identifier supplied");
1910   }
1911     
1912   string ident = naStr_data(args[argOffset++]);
1913   WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1914   
1915 // set waypt flags - approach, departure, pseudo, etc
1916   if (argc > argOffset) {
1917     WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1918     wpt->setFlag(f);
1919   }
1920   
1921   return ghostForWaypt(c, wpt);
1922 }
1923
1924 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1925 {
1926   if (argc < 1) {
1927     naRuntimeError(c, "createWPFrom: need at least one argument");
1928   }
1929   
1930   FGPositioned* positioned = positionedGhost(args[0]);
1931   if (!positioned) {
1932     naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1933   }
1934   
1935   WayptRef wpt;
1936   if (positioned->type() == FGPositioned::RUNWAY) {
1937     wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1938   } else {
1939     wpt = new NavaidWaypoint(positioned, NULL);
1940   }
1941
1942   // set waypt flags - approach, departure, pseudo, etc
1943   if (argc > 1) {
1944     WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1945     wpt->setFlag(f);
1946   }
1947   
1948   return ghostForWaypt(c, wpt);
1949 }
1950
1951 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1952 {
1953   FlightPlan* fp = flightplanGhost(me);
1954   if (!fp) {
1955     naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1956   }
1957
1958   int index;
1959   if (argc == 0) {
1960     index = fp->currentIndex();
1961   } else {
1962     index = (int) naNumValue(args[0]).num;
1963   }
1964   
1965   if ((index < 0) || (index >= fp->numLegs())) {
1966     return naNil();
1967   }
1968   
1969   return ghostForLeg(c, fp->legAtIndex(index));
1970 }
1971
1972 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1973 {
1974   FlightPlan* fp = flightplanGhost(me);
1975   if (!fp) {
1976     naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1977   }
1978   return ghostForLeg(c, fp->currentLeg());
1979 }
1980
1981 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1982 {
1983   FlightPlan* fp = flightplanGhost(me);
1984   if (!fp) {
1985     naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1986   }
1987   return ghostForLeg(c, fp->nextLeg());
1988 }
1989
1990 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1991 {
1992   FlightPlan* fp = flightplanGhost(me);
1993   if (!fp) {
1994     naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1995   }
1996   return naNum(fp->numLegs());
1997 }
1998
1999 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2000 {
2001   FlightPlan* fp = flightplanGhost(me);
2002   if (!fp) {
2003     naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2004   }
2005   
2006   WayptRef wp = wayptGhost(args[0]);
2007   int index = fp->numLegs();
2008   fp->insertWayptAtIndex(wp.get(), index);
2009   return naNum(index);
2010 }
2011
2012 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2013 {
2014   FlightPlan* fp = flightplanGhost(me);
2015   if (!fp) {
2016     naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2017   }
2018   
2019   WayptRef wp = wayptGhost(args[0]);
2020   int index = -1; // append
2021   if ((argc > 1) && naIsNum(args[1])) {
2022     index = (int) args[1].num;
2023   }
2024   
2025   fp->insertWayptAtIndex(wp.get(), index);
2026   return naNil();
2027 }
2028
2029 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2030 {
2031   FlightPlan* fp = flightplanGhost(me);
2032   if (!fp) {
2033     naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2034   }
2035   
2036   WayptRef wp = wayptGhost(args[0]);
2037   int index = -1; // append
2038   if ((argc > 1) && naIsNum(args[1])) {
2039     index = (int) args[1].num;
2040   }
2041   
2042   fp->insertWayptAtIndex(wp.get(), index + 1);
2043   return naNil();
2044 }
2045
2046 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2047 {
2048   FlightPlan* fp = flightplanGhost(me);
2049   if (!fp) {
2050     naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2051   }
2052   
2053   WayptVec wps;
2054   if (!naIsVector(args[0])) {
2055     naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2056   }
2057
2058   int count = naVec_size(args[0]);
2059   for (int i=0; i<count; ++i) {
2060     Waypt* wp = wayptGhost(naVec_get(args[0], i));
2061     if (wp) {
2062       wps.push_back(wp);
2063     }
2064   }
2065   
2066   int index = -1; // append
2067   if ((argc > 1) && naIsNum(args[1])) {
2068     index = (int) args[1].num;
2069   }
2070
2071   fp->insertWayptsAtIndex(wps, index);
2072   return naNil();
2073 }
2074
2075 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2076 {
2077   FlightPlan* fp = flightplanGhost(me);
2078   if (!fp) {
2079     naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2080   }
2081   
2082   if ((argc < 1) || !naIsNum(args[0])) {
2083     naRuntimeError(c, "bad argument to flightplan.deleteWP");
2084   }
2085   
2086   int index = (int) args[0].num;
2087   fp->deleteIndex(index);
2088   return naNil();
2089 }
2090
2091 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2092 {
2093   FlightPlan* fp = flightplanGhost(me);
2094   if (!fp) {
2095     naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2096   }
2097   
2098   fp->clear();
2099   return naNil();
2100 }
2101
2102 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2103 {
2104   FlightPlan* fp = flightplanGhost(me);
2105   if (!fp) {
2106     naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2107   }
2108   
2109   if (argc < 1) {
2110     naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2111   }
2112   
2113   WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2114   fp->clearWayptsWithFlag(flag);
2115   return naNil();
2116 }
2117
2118 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2119 {
2120   FlightPlan* fp = flightplanGhost(me);
2121   if (!fp) {
2122     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2123   }
2124   
2125   return ghostForFlightPlan(c, fp->clone());
2126 }
2127
2128 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2129 {
2130   FlightPlan::Leg* leg = fpLegGhost(me);
2131   if (!leg) {
2132     naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2133   }
2134   
2135   if (argc < 2) {
2136     naRuntimeError(c, "bad arguments to leg.setSpeed");
2137   }
2138   
2139   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2140   leg->setSpeed(rr, args[0].num);
2141   return naNil();
2142 }
2143
2144 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2145 {
2146   FlightPlan::Leg* leg = fpLegGhost(me);
2147   if (!leg) {
2148     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2149   }
2150   
2151   if (argc < 2) {
2152     naRuntimeError(c, "bad arguments to leg.setAltitude");
2153   }
2154   
2155   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2156   leg->setAltitude(rr, args[0].num);
2157   return naNil();
2158 }
2159
2160 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2161 {
2162   FlightPlan::Leg* leg = fpLegGhost(me);
2163   if (!leg) {
2164     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2165   }
2166   
2167   RoutePath path(leg->owner());
2168   SGGeodVec gv(path.pathForIndex(leg->index()));
2169
2170   naRef result = naNewVector(c);
2171   BOOST_FOREACH(SGGeod p, gv) {
2172     // construct a geo.Coord!
2173     naRef coord = naNewHash(c);
2174     hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2175     hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2176     naVec_append(result, coord);
2177   }
2178
2179   return result;
2180 }
2181
2182 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2183 {
2184   flightgear::Waypt* w = wayptGhost(me);
2185   if (!w) {
2186     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2187   }
2188   
2189   FGPositioned* pos = w->source();
2190   if (!pos) {
2191     return naNil();
2192   }
2193   
2194   switch (pos->type()) {
2195   case FGPositioned::VOR:
2196   case FGPositioned::NDB:
2197   case FGPositioned::ILS:
2198   case FGPositioned::LOC:
2199   case FGPositioned::GS:
2200   case FGPositioned::DME:
2201   case FGPositioned::TACAN: {
2202     FGNavRecord* nav = (FGNavRecord*) pos;
2203     return ghostForNavaid(c, nav);
2204   }
2205       
2206   default:
2207     return naNil();
2208   }
2209 }
2210
2211 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2212 {
2213   flightgear::Waypt* w = wayptGhost(me);
2214   if (!w) {
2215     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2216   }
2217   
2218   FGPositioned* pos = w->source();
2219   if (!pos || FGAirport::isAirportType(pos)) {
2220     return naNil();
2221   }
2222   
2223   return ghostForAirport(c, (FGAirport*) pos);
2224 }
2225
2226 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2227 {
2228   flightgear::Waypt* w = wayptGhost(me);
2229   if (!w) {
2230     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2231   }
2232   
2233   FGPositioned* pos = w->source();
2234   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2235     return naNil();
2236   }
2237   
2238   return ghostForRunway(c, (FGRunway*) pos);
2239 }
2240
2241 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2242 {
2243   Procedure* proc = procedureGhost(me);
2244   if (!proc) {
2245     naRuntimeError(c, "procedure.transition called on non-procedure object");
2246   }
2247   
2248   if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2249     naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2250   }
2251   
2252   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2253   Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2254   
2255   return ghostForProcedure(c, trans);
2256 }
2257
2258 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2259 {
2260   Procedure* proc = procedureGhost(me);
2261   if (!proc) {
2262     naRuntimeError(c, "procedure.route called on non-procedure object");
2263   }
2264   
2265 // wrapping up tow different routines here - approach routing from the IAF
2266 // to the associated runway, and SID/STAR routing via an enroute transition
2267 // and possibly a runway transition or not.
2268   if (Approach::isApproach(proc->type())) {
2269     WayptRef iaf;
2270     if (argc > 0) {
2271       iaf = wayptFromArg(args[0]);
2272     }
2273     
2274     WayptVec r;
2275     Approach* app = (Approach*) proc;
2276     if (!app->route(iaf, r)) {
2277       SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2278       return naNil();
2279     }
2280     
2281     return convertWayptVecToNasal(c, r);
2282   } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2283     naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2284   }
2285   
2286   int argOffset = 0;
2287   FGRunway* rwy = runwayGhost(args[0]);
2288   if (rwy) ++argOffset;
2289   
2290   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2291   Transition* trans = NULL;
2292   if (argOffset < argc) {
2293     trans = (Transition*) procedureGhost(args[argOffset]);
2294   }
2295   
2296   // note either runway or trans may be NULL - that's ok
2297   WayptVec r;
2298   if (!ad->route(rwy, trans, r)) {
2299     SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2300     return naNil();
2301   }
2302   
2303   return convertWayptVecToNasal(c, r);
2304 }
2305
2306
2307 // Table of extension functions.  Terminate with zeros.
2308 static struct { const char* name; naCFunction func; } funcs[] = {
2309   { "carttogeod", f_carttogeod },
2310   { "geodtocart", f_geodtocart },
2311   { "geodinfo", f_geodinfo },
2312   { "airportinfo", f_airportinfo },
2313   { "findAirportsWithinRange", f_findAirportsWithinRange },
2314   { "findAirportsByICAO", f_findAirportsByICAO },
2315   { "navinfo", f_navinfo },
2316   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2317   { "findNavaidByFrequency", f_findNavaidByFrequency },
2318   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2319   { "findNavaidsByID", f_findNavaidsByIdent },
2320   { "findFixesByID", f_findFixesByIdent },
2321   { "flightplan", f_route },
2322   { "registerFlightPlanDelegate", f_registerFPDelegate },
2323   { "createWP", f_createWP },
2324   { "createWPFrom", f_createWPFrom },
2325   { "airwaysRoute", f_airwaySearch },
2326   { "magvar", f_magvar },
2327   { "courseAndDistance", f_courseAndDistance },
2328   { "greatCircleMove", f_greatCircleMove },
2329   { "tileIndex", f_tileIndex },
2330   { "tilePath", f_tilePath },
2331   { 0, 0 }
2332 };
2333
2334
2335 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2336 {
2337     airportPrototype = naNewHash(c);
2338     hashset(c, gcSave, "airportProto", airportPrototype);
2339   
2340     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2341     hashset(c, airportPrototype, "taxiway", naNewFunc(c, naNewCCode(c, f_airport_taxiway)));
2342     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2343     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2344     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2345     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2346     hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2347     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2348     hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2349     hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2350     hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2351     hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2352   
2353     flightplanPrototype = naNewHash(c);
2354     hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2355       
2356     hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2357     hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP))); 
2358     hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP))); 
2359     hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2360     hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP))); 
2361     hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP))); 
2362     hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP))); 
2363     hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter))); 
2364     hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints))); 
2365     hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan))); 
2366     hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType))); 
2367     hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone))); 
2368   
2369     waypointPrototype = naNewHash(c);
2370     hashset(c, gcSave, "wayptProto", waypointPrototype);
2371     
2372     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2373     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2374     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2375   
2376     procedurePrototype = naNewHash(c);
2377     hashset(c, gcSave, "procedureProto", procedurePrototype);
2378     hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2379     hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2380   
2381     fpLegPrototype = naNewHash(c);
2382     hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2383     hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2384     hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2385     hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2386   
2387     for(int i=0; funcs[i].name; i++) {
2388       hashset(c, globals, funcs[i].name,
2389       naNewFunc(c, naNewCCode(c, funcs[i].func)));
2390     }
2391   
2392   return naNil();
2393 }
2394
2395 void postinitNasalPositioned(naRef globals, naContext c)
2396 {
2397   naRef geoModule = naHash_cget(globals, (char*) "geo");
2398   if (naIsNil(geoModule)) {
2399     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2400     return;
2401   }
2402   
2403   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
2404 }
2405
2406