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