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