1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 James Turner
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.
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.
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.
27 #include "NasalPositioned.hxx"
29 #include <boost/foreach.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <boost/tuple/tuple.hpp> // for boost::tie
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>
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>
59 using namespace flightgear;
61 static void positionedGhostDestroy(void* g);
62 static void wayptGhostDestroy(void* g);
63 static void legGhostDestroy(void* g);
64 static void routeBaseGhostDestroy(void* g);
66 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
68 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
69 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
71 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
72 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
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 };
79 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
80 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
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);
85 naGhostType WayptGhostType = { wayptGhostDestroy,
88 waypointGhostSetMember};
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);
93 naGhostType FPLegGhostType = { legGhostDestroy,
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);
101 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy,
103 flightplanGhostGetMember,
104 flightplanGhostSetMember
107 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
108 naGhostType ProcedureGhostType = { routeBaseGhostDestroy,
110 procedureGhostGetMember,
113 static void hashset(naContext c, naRef hash, const char* key, naRef val)
115 naRef s = naNewString(c);
116 naStr_fromdata(s, (char*)key, strlen(key));
117 naHash_set(hash, s, val);
120 static naRef stringToNasal(naContext c, const std::string& s)
122 return naStr_fromdata(naNewString(c),
123 const_cast<char *>(s.c_str()),
127 static WayptFlag wayptFlagFromString(const char* s)
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;
135 return (WayptFlag) 0;
138 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
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");
148 static FGPositioned* positionedGhost(naRef r)
150 if ((naGhost_type(r) == &AirportGhostType) ||
151 (naGhost_type(r) == &NavaidGhostType) ||
152 (naGhost_type(r) == &RunwayGhostType) ||
153 (naGhost_type(r) == &FixGhostType))
155 return (FGPositioned*) naGhost_ptr(r);
161 static FGAirport* airportGhost(naRef r)
163 if (naGhost_type(r) == &AirportGhostType)
164 return (FGAirport*) naGhost_ptr(r);
168 static FGNavRecord* navaidGhost(naRef r)
170 if (naGhost_type(r) == &NavaidGhostType)
171 return (FGNavRecord*) naGhost_ptr(r);
175 static FGRunway* runwayGhost(naRef r)
177 if (naGhost_type(r) == &RunwayGhostType)
178 return (FGRunway*) naGhost_ptr(r);
182 static FGTaxiway* taxiwayGhost(naRef r)
184 if (naGhost_type(r) == &TaxiwayGhostType)
185 return (FGTaxiway*) naGhost_ptr(r);
189 static FGFix* fixGhost(naRef r)
191 if (naGhost_type(r) == &FixGhostType)
192 return (FGFix*) naGhost_ptr(r);
197 static void positionedGhostDestroy(void* g)
199 FGPositioned* pos = (FGPositioned*)g;
200 if (!FGPositioned::put(pos)) // unref
204 static Waypt* wayptGhost(naRef r)
206 if (naGhost_type(r) == &WayptGhostType)
207 return (Waypt*) naGhost_ptr(r);
209 if (naGhost_type(r) == &FPLegGhostType) {
210 FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
211 return leg->waypoint();
217 static void wayptGhostDestroy(void* g)
219 Waypt* wpt = (Waypt*)g;
220 if (!Waypt::put(wpt)) // unref
224 static void legGhostDestroy(void* g)
230 static FlightPlan::Leg* fpLegGhost(naRef r)
232 if (naGhost_type(r) == &FPLegGhostType)
233 return (FlightPlan::Leg*) naGhost_ptr(r);
237 static Procedure* procedureGhost(naRef r)
239 if (naGhost_type(r) == &ProcedureGhostType)
240 return (Procedure*) naGhost_ptr(r);
244 static FlightPlan* flightplanGhost(naRef r)
246 if (naGhost_type(r) == &FlightPlanGhostType)
247 return (FlightPlan*) naGhost_ptr(r);
251 static void routeBaseGhostDestroy(void* g)
256 static naRef airportPrototype;
257 static naRef flightplanPrototype;
258 static naRef waypointPrototype;
259 static naRef geoCoordClass;
260 static naRef fpLegPrototype;
261 static naRef procedurePrototype;
263 naRef ghostForAirport(naContext c, const FGAirport* apt)
269 FGPositioned::get(apt); // take a ref
270 return naNewGhost2(c, &AirportGhostType, (void*) apt);
273 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
279 FGPositioned::get(n); // take a ref
280 return naNewGhost2(c, &NavaidGhostType, (void*) n);
283 naRef ghostForRunway(naContext c, const FGRunway* r)
289 FGPositioned::get(r); // take a ref
290 return naNewGhost2(c, &RunwayGhostType, (void*) r);
293 naRef ghostForHelipad(naContext c, const FGHelipad* r)
299 FGPositioned::get(r); // take a ref
300 return naNewGhost2(c, &HelipadGhostType, (void*) r);
303 naRef ghostForTaxiway(naContext c, const FGTaxiway* r)
309 FGPositioned::get(r); // take a ref
310 return naNewGhost2(c, &TaxiwayGhostType, (void*) r);
313 naRef ghostForFix(naContext c, const FGFix* r)
319 FGPositioned::get(r); // take a ref
320 return naNewGhost2(c, &FixGhostType, (void*) r);
324 naRef ghostForWaypt(naContext c, const Waypt* wpt)
330 Waypt::get(wpt); // take a ref
331 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
334 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
340 return naNewGhost2(c, &FPLegGhostType, (void*) leg);
343 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
349 return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
352 naRef ghostForProcedure(naContext c, const Procedure* proc)
358 return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
361 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
363 const char* fieldName = naStr_data(field);
364 FGAirport* apt = (FGAirport*) g;
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")) {
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) {
386 naRef rwyid = stringToNasal(c, rwy->ident());
387 naRef rwydata = ghostForRunway(c, rwy);
388 naHash_set(*out, rwyid, rwydata);
390 } else if (!strcmp(fieldName, "helipads")) {
393 for(unsigned int r=0; r<apt->numHelipads(); ++r) {
394 FGHelipad* hp(apt->getHelipadByIndex(r));
396 naRef rwyid = stringToNasal(c, hp->ident());
397 naRef rwydata = ghostForHelipad(c, hp);
398 naHash_set(*out, rwyid, rwydata);
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);
416 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
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");
433 *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
436 return NULL; // member not found
442 static void waypointCommonSetMember(naContext c, Waypt* wpt, const char* fieldName, naRef value)
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));
449 naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
452 wpt->setFlag(f, true);
456 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
458 const char* fieldName = naStr_data(field);
459 Waypt* wpt = (flightgear::Waypt*) g;
460 return waypointCommonGetMember(c, wpt, fieldName, out);
463 static RouteRestriction routeRestrictionFromString(const char* s)
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;
475 naRef routeRestrictionToNasal(naContext c, RouteRestriction 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");
491 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
493 const char* fieldName = naStr_data(field);
494 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
495 Waypt* wpt = leg->waypoint();
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();
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);
521 return ""; // success
524 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
526 const char* fieldName = naStr_data(field);
527 Waypt* wpt = (Waypt*) g;
528 waypointCommonSetMember(c, wpt, fieldName, value);
531 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
533 const char* fieldName = naStr_data(field);
534 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
536 waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
539 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
541 const char* fieldName = naStr_data(field);
542 FlightPlan* fp = (FlightPlan*) g;
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());
565 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
567 const char* fieldName = naStr_data(field);
568 FlightPlan* fp = (FlightPlan*) g;
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())) {
578 fp->setCurrentIndex(index);
579 } else if (!strcmp(fieldName, "departure")) {
580 FGAirport* apt = airportGhost(value);
582 fp->setDeparture(apt);
586 FGRunway* rwy = runwayGhost(value);
588 fp->setDeparture(rwy);
592 naRuntimeError(c, "bad argument type setting departure");
593 } else if (!strcmp(fieldName, "destination")) {
594 FGAirport* apt = airportGhost(value);
596 fp->setDestination(apt);
600 FGRunway* rwy = runwayGhost(value);
602 fp->setDestination(rwy);
606 naRuntimeError(c, "bad argument type setting destination");
607 } else if (!strcmp(fieldName, "departure_runway")) {
608 FGRunway* rwy = runwayGhost(value);
610 fp->setDeparture(rwy);
614 naRuntimeError(c, "bad argument type setting departure");
615 } else if (!strcmp(fieldName, "destination_runway")) {
616 FGRunway* rwy = runwayGhost(value);
618 fp->setDestination(rwy);
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);
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);
635 if (naIsString(value)) {
636 FGAirport* apt = fp->departureAirport();
637 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
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);
649 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
650 fp->setSTAR((Transition*) proc);
654 if (naIsString(value)) {
655 FGAirport* apt = fp->destinationAirport();
656 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
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);
668 if (naIsString(value)) {
669 FGAirport* apt = fp->destinationAirport();
670 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
674 naRuntimeError(c, "bad argument type setting approach");
679 static naRef procedureTpType(naContext c, ProcedureType 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");
694 static naRef procedureRadioType(naContext c, ProcedureType 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");
706 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
708 const char* fieldName = naStr_data(field);
709 Procedure* proc = (Procedure*) g;
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()));
723 } else if (!strcmp(fieldName, "transitions")) {
724 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
729 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
730 *out = naNewVector(c);
731 BOOST_FOREACH(string id, ad->transitionIdents()) {
732 naVec_append(*out, stringToNasal(c, id));
741 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
743 const char* fieldName = naStr_data(field);
744 FGRunwayBase* base = (FGRunwayBase*) g;
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());
773 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
775 const char* fieldName = naStr_data(field);
776 FGNavRecord* nav = (FGNavRecord*) g;
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);
805 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
807 const char* fieldName = naStr_data(field);
808 FGFix* fix = (FGFix*) g;
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());
820 static bool hashIsCoord(naRef h)
822 naRef parents = naHash_cget(h, (char*) "parents");
823 if (!naIsVector(parents)) {
827 return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
830 bool geodFromHash(naRef ref, SGGeod& result)
832 if (!naIsHash(ref)) {
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);
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);
854 // check for any synonyms?
855 // latitude + longitude?
860 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
862 if (offset >= argc) {
866 if (naIsGhost(args[offset])) {
867 naGhostType* gt = naGhost_type(args[offset]);
868 if (gt == &AirportGhostType) {
869 result = airportGhost(args[offset])->geod();
873 if (gt == &NavaidGhostType) {
874 result = navaidGhost(args[offset])->geod();
878 if (gt == &RunwayGhostType) {
879 result = runwayGhost(args[offset])->geod();
883 if (gt == &TaxiwayGhostType) {
884 result = taxiwayGhost(args[offset])->geod();
888 if (gt == &FixGhostType) {
889 result = fixGhost(args[offset])->geod();
893 if (gt == &WayptGhostType) {
894 result = wayptGhost(args[offset])->position();
899 if (geodFromHash(args[offset], result)) {
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);
913 // Convert a cartesian point to a geodetic lat/lon/altitude.
914 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
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));
930 // Convert a geodetic lat/lon/altitude to a cartesian point.
931 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
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;
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]));
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
950 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
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))
962 const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
963 naRef vec = naNewVector(c);
964 naVec_append(vec, naNum(elev));
965 naRef matdata = naNil();
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));
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()));
980 naVec_append(vec, matdata);
986 class AirportInfoFilter : public FGAirport::AirportFilter
989 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
990 minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
993 bool fromArg(naRef arg)
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;
1005 virtual FGPositioned::Type minType() const {
1009 virtual FGPositioned::Type maxType() const {
1013 virtual bool pass(FGPositioned* aPos) const
1015 FGAirport* apt = (FGAirport*) aPos;
1016 if ((apt->type() == FGPositioned::AIRPORT) &&
1017 !apt->hasHardRunwayOfLengthFt(minRunwayLengthFt))
1025 FGPositioned::Type type;
1026 double minRunwayLengthFt;
1029 // Returns data hash for particular or nearest airport of a <type>, or nil
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)
1038 SGGeod pos = globals->get_aircraft_position();
1039 FGAirport* apt = NULL;
1041 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1042 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1047 double maxRange = 10000.0; // expose this? or pick a smaller value?
1049 AirportInfoFilter filter; // defaults to airports only
1052 // fall through and use AIRPORT
1053 } else if(argc == 1 && naIsString(args[0])) {
1054 if (filter.fromArg(args[0])) {
1057 // user provided an <id>, hopefully
1058 apt = FGAirport::findByIdent(naStr_data(args[0]));
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.
1067 naRuntimeError(c, "airportinfo() with invalid function arguments");
1072 apt = FGAirport::findClosest(pos, maxRange, &filter);
1073 if(!apt) return naNil();
1076 return ghostForAirport(c, apt);
1079 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1082 SGGeod pos = globals->get_aircraft_position();
1083 argOffset += geodFromArgs(args, 0, argc, pos);
1085 if (!naIsNum(args[argOffset])) {
1086 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1089 AirportInfoFilter filter; // defaults to airports only
1090 double rangeNm = args[argOffset++].num;
1091 if (argOffset < argc) {
1092 filter.fromArg(args[argOffset++]);
1095 naRef r = naNewVector(c);
1097 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1098 FGPositioned::sortByRange(apts, pos);
1100 BOOST_FOREACH(FGPositionedRef a, apts) {
1101 FGAirport* apt = (FGAirport*) a.get();
1102 naVec_append(r, ghostForAirport(c, apt));
1108 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1110 if (!naIsString(args[0])) {
1111 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1115 string prefix(naStr_data(args[argOffset++]));
1116 AirportInfoFilter filter; // defaults to airports only
1117 if (argOffset < argc) {
1118 filter.fromArg(args[argOffset++]);
1121 naRef r = naNewVector(c);
1123 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1125 BOOST_FOREACH(FGPositionedRef a, apts) {
1126 FGAirport* apt = (FGAirport*) a.get();
1127 naVec_append(r, ghostForAirport(c, apt));
1133 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1135 FGAirport* apt = airportGhost(me);
1137 naRuntimeError(c, "airport.tower called on non-airport object");
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()));
1149 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1151 FGAirport* apt = airportGhost(me);
1153 naRuntimeError(c, "airport.comms called on non-airport object");
1155 naRef comms = naNewVector(c);
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);
1162 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1163 naVec_append(comms, naNum(comm->freqMHz()));
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);
1178 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1180 FGAirport* apt = airportGhost(me);
1182 naRuntimeError(c, "airport.runway called on non-airport object");
1185 if ((argc < 1) || !naIsString(args[0])) {
1186 naRuntimeError(c, "airport.runway expects a runway ident argument");
1189 std::string ident(naStr_data(args[0]));
1190 boost::to_upper(ident);
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));
1200 static naRef f_airport_runwaysWithoutReciprocals(naContext c, naRef me, int argc, naRef* args)
1202 FGAirport* apt = airportGhost(me);
1204 naRuntimeError(c, "airport.runwaysWithoutReciprocals called on non-airport object");
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())));
1216 static naRef f_airport_taxiway(naContext c, naRef me, int argc, naRef* args)
1218 FGAirport* apt = airportGhost(me);
1220 naRuntimeError(c, "airport.taxiway called on non-airport object");
1223 if ((argc < 1) || !naIsString(args[0])) {
1224 naRuntimeError(c, "airport.taxiway expects a taxiway ident argument");
1227 naRef taxiways = naNewVector(c);
1229 for (unsigned int i = 0; i < apt->numTaxiways(); i++) {
1230 naVec_append(taxiways, ghostForTaxiway(c, apt->getTaxiwayByIndex(i)));
1236 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1238 FGAirport* apt = airportGhost(me);
1240 naRuntimeError(c, "airport.sids called on non-airport object");
1243 naRef sids = naNewVector(c);
1245 FGRunway* rwy = NULL;
1246 if (argc > 0 && naIsString(args[0])) {
1247 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1251 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1252 } else if (argc > 0) {
1253 rwy = runwayGhost(args[0]);
1257 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1258 naRef procId = stringToNasal(c, sid->ident());
1259 naVec_append(sids, procId);
1262 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1263 flightgear::SID* sid = apt->getSIDByIndex(s);
1264 naRef procId = stringToNasal(c, sid->ident());
1265 naVec_append(sids, procId);
1272 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1274 FGAirport* apt = airportGhost(me);
1276 naRuntimeError(c, "airport.stars called on non-airport object");
1279 naRef stars = naNewVector(c);
1281 FGRunway* rwy = NULL;
1282 if (argc > 0 && naIsString(args[0])) {
1283 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1287 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1288 } else if (argc > 0) {
1289 rwy = runwayGhost(args[0]);
1293 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1294 naRef procId = stringToNasal(c, s->ident());
1295 naVec_append(stars, procId);
1298 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1299 flightgear::STAR* star = apt->getSTARByIndex(s);
1300 naRef procId = stringToNasal(c, star->ident());
1301 naVec_append(stars, procId);
1308 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1310 FGAirport* apt = airportGhost(me);
1312 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1315 naRef approaches = naNewVector(c);
1317 ProcedureType ty = PROCEDURE_INVALID;
1318 if ((argc > 1) && naIsString(args[1])) {
1319 std::string u(naStr_data(args[1]));
1321 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1322 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1323 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1324 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1327 FGRunway* rwy = NULL;
1328 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1330 } else if (argc > 0 && naIsString(args[0])) {
1331 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1335 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1339 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1340 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1344 naRef procId = stringToNasal(c, s->ident());
1345 naVec_append(approaches, procId);
1348 // no runway specified, report them all
1349 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1350 Approach* app = apt->getApproachByIndex(s);
1351 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1355 naRef procId = stringToNasal(c, app->ident());
1356 naVec_append(approaches, procId);
1363 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1365 FGAirport* apt = airportGhost(me);
1367 naRuntimeError(c, "airport.parking called on non-airport object");
1370 naRef r = naNewVector(c);
1372 bool onlyAvailable = false;
1374 if (argc > 0 && naIsString(args[0])) {
1375 type = naStr_data(args[0]);
1378 if ((argc > 1) && naIsNum(args[1])) {
1379 onlyAvailable = (args[1].num != 0.0);
1382 FGAirportDynamics* dynamics = apt->getDynamics();
1383 PositionedIDVec parkings = flightgear::NavDataCache::instance()->airportItemsOfType(apt->guid(),
1384 FGPositioned::PARKING);
1386 BOOST_FOREACH(PositionedID parking, parkings) {
1387 // filter out based on availability and type
1388 if (onlyAvailable && !dynamics->isParkingAvailable(parking)) {
1392 FGParking* park = dynamics->getParking(parking);
1393 if (!type.empty() && (park->getType() != type)) {
1397 const SGGeod& parkLoc = park->geod();
1398 naRef ph = naNewHash(c);
1399 hashset(c, ph, "name", stringToNasal(c, park->getName()));
1400 hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1401 hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1402 hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1403 naVec_append(r, ph);
1409 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1411 FGAirport* apt = airportGhost(me);
1413 naRuntimeError(c, "airport.getSid called on non-airport object");
1416 if ((argc != 1) || !naIsString(args[0])) {
1417 naRuntimeError(c, "airport.getSid passed invalid argument");
1420 string ident = naStr_data(args[0]);
1421 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1424 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1426 FGAirport* apt = airportGhost(me);
1428 naRuntimeError(c, "airport.getStar called on non-airport object");
1431 if ((argc != 1) || !naIsString(args[0])) {
1432 naRuntimeError(c, "airport.getStar passed invalid argument");
1435 string ident = naStr_data(args[0]);
1436 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1439 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1441 FGAirport* apt = airportGhost(me);
1443 naRuntimeError(c, "airport.getIAP called on non-airport object");
1446 if ((argc != 1) || !naIsString(args[0])) {
1447 naRuntimeError(c, "airport.getIAP passed invalid argument");
1450 string ident = naStr_data(args[0]);
1451 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1454 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1456 FGAirport* apt = airportGhost(me);
1458 naRuntimeError(c, "airport.tostring called on non-airport object");
1461 return stringToNasal(c, "an airport " + apt->ident());
1464 // Returns vector of data hash for navaid of a <type>, nil on error
1465 // navaids sorted by ascending distance
1466 // navinfo([<lat>,<lon>],[<type>],[<id>])
1467 // lat/lon (numeric): use latitude/longitude instead of ac position
1468 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1469 // id: (partial) id of the fix
1471 // navinfo("vor") returns all vors
1472 // navinfo("HAM") return all navaids who's name start with "HAM"
1473 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1474 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1475 // sorted by distance relative to lat=34, lon=48
1476 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1480 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1481 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1485 pos = globals->get_aircraft_position();
1488 FGPositioned::Type type = FGPositioned::INVALID;
1489 nav_list_type navlist;
1490 const char * id = "";
1492 if(argc > 0 && naIsString(args[0])) {
1493 const char *s = naStr_data(args[0]);
1494 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1495 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1496 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1497 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1498 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1499 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1500 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1501 else id = s; // this is an id
1506 if(argc > 0 && naIsString(args[0])) {
1508 naRuntimeError(c, "navinfo() called with navaid id");
1511 id = naStr_data(args[0]);
1517 naRuntimeError(c, "navinfo() called with too many arguments");
1521 FGNavList::TypeFilter filter(type);
1522 navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1524 naRef reply = naNewVector(c);
1525 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1526 naVec_append( reply, ghostForNavaid(c, *it) );
1531 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1534 SGGeod pos = globals->get_aircraft_position();
1535 argOffset += geodFromArgs(args, 0, argc, pos);
1537 if (!naIsNum(args[argOffset])) {
1538 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1541 FGPositioned::Type type = FGPositioned::INVALID;
1542 double rangeNm = args[argOffset++].num;
1543 if (argOffset < argc) {
1544 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1547 naRef r = naNewVector(c);
1548 FGNavList::TypeFilter filter(type);
1549 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1550 FGPositioned::sortByRange(navs, pos);
1552 BOOST_FOREACH(FGPositionedRef a, navs) {
1553 FGNavRecord* nav = (FGNavRecord*) a.get();
1554 naVec_append(r, ghostForNavaid(c, nav));
1560 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1563 SGGeod pos = globals->get_aircraft_position();
1564 argOffset += geodFromArgs(args, 0, argc, pos);
1566 if (!naIsNum(args[argOffset])) {
1567 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1570 FGPositioned::Type type = FGPositioned::INVALID;
1571 double freqMhz = args[argOffset++].num;
1572 if (argOffset < argc) {
1573 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1576 FGNavList::TypeFilter filter(type);
1577 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1582 return ghostForNavaid(c, navs.front().ptr());
1585 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1588 SGGeod pos = globals->get_aircraft_position();
1589 argOffset += geodFromArgs(args, 0, argc, pos);
1591 if (!naIsNum(args[argOffset])) {
1592 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1595 FGPositioned::Type type = FGPositioned::INVALID;
1596 double freqMhz = args[argOffset++].num;
1597 if (argOffset < argc) {
1598 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1601 naRef r = naNewVector(c);
1603 FGNavList::TypeFilter filter(type);
1604 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1606 BOOST_FOREACH(nav_rec_ptr a, navs) {
1607 naVec_append(r, ghostForNavaid(c, a.ptr()));
1613 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1616 SGGeod pos = globals->get_aircraft_position();
1617 argOffset += geodFromArgs(args, 0, argc, pos);
1619 if (!naIsString(args[argOffset])) {
1620 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1623 FGPositioned::Type type = FGPositioned::INVALID;
1624 string ident = naStr_data(args[argOffset++]);
1625 if (argOffset < argc) {
1626 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1629 FGNavList::TypeFilter filter(type);
1630 naRef r = naNewVector(c);
1631 nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1633 BOOST_FOREACH(nav_rec_ptr a, navs) {
1634 naVec_append(r, ghostForNavaid(c, a.ptr()));
1640 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1643 SGGeod pos = globals->get_aircraft_position();
1644 argOffset += geodFromArgs(args, 0, argc, pos);
1646 if (!naIsString(args[argOffset])) {
1647 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1650 string ident(naStr_data(args[argOffset]));
1651 naRef r = naNewVector(c);
1653 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1654 FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1655 FGPositioned::sortByRange(fixes, pos);
1657 BOOST_FOREACH(FGPositionedRef f, fixes) {
1658 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1664 // Convert a cartesian point to a geodetic lat/lon/altitude.
1665 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1667 SGGeod pos = globals->get_aircraft_position();
1669 // fine, use aircraft position
1670 } else if (geodFromArgs(args, 0, argc, pos)) {
1673 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1676 double jd = globals->get_time_params()->getJD();
1677 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1678 return naNum(magvarDeg);
1681 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1683 SGGeod from = globals->get_aircraft_position(), to, p;
1684 int argOffset = geodFromArgs(args, 0, argc, p);
1685 if (geodFromArgs(args, argOffset, argc, to)) {
1686 from = p; // we parsed both FROM and TO args, so first was from
1688 to = p; // only parsed one arg, so FROM is current
1691 if (argOffset == 0) {
1692 naRuntimeError(c, "invalid arguments to courseAndDistance");
1695 double course, course2, d;
1696 SGGeodesy::inverse(from, to, course, course2, d);
1698 naRef result = naNewVector(c);
1699 naVec_append(result, naNum(course));
1700 naVec_append(result, naNum(d * SG_METER_TO_NM));
1704 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1706 SGGeod from = globals->get_aircraft_position(), to;
1709 // complication - don't inerpret two doubles (as the only args)
1710 // as a lat,lon pair - only do so if we have at least three args.
1712 argOffset = geodFromArgs(args, 0, argc, from);
1715 if ((argOffset + 1) >= argc) {
1716 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1719 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1720 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1721 argOffset, argOffset + 1);
1724 double course = args[argOffset].num, course2;
1725 double distanceNm = args[argOffset + 1].num;
1726 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1729 naRef coord = naNewHash(c);
1730 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1731 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1735 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1737 SGGeod pos = globals->get_aircraft_position();
1738 geodFromArgs(args, 0, argc, pos);
1740 return stringToNasal(c, b.gen_base_path());
1743 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1745 SGGeod pos = globals->get_aircraft_position();
1746 geodFromArgs(args, 0, argc, pos);
1748 return naNum(b.gen_index());
1751 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1754 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1755 return ghostForFlightPlan(c, rm->flightPlan());
1758 if ((argc > 0) && naIsString(args[0])) {
1759 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1760 SGPath path(naStr_data(args[0]));
1761 if (!path.exists()) {
1762 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1765 if (!fp->load(path)) {
1766 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1771 return ghostForFlightPlan(c, fp);
1774 naRuntimeError(c, "bad arguments to flightplan()");
1778 class NasalFPDelegate : public FlightPlan::Delegate
1781 NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1786 SG_LOG(SG_NASAL, SG_INFO, "created Nasal delegate for " << fp);
1787 _gcSaveKey = _nasal->gcSave(ins);
1790 virtual ~NasalFPDelegate()
1792 SG_LOG(SG_NASAL, SG_INFO, "destroying Nasal delegate for " << _plan);
1793 _nasal->gcRelease(_gcSaveKey);
1796 virtual void departureChanged()
1798 callDelegateMethod("departureChanged");
1801 virtual void arrivalChanged()
1803 callDelegateMethod("arrivalChanged");
1806 virtual void waypointsChanged()
1808 callDelegateMethod("waypointsChanged");
1811 virtual void currentWaypointChanged()
1813 callDelegateMethod("currentWaypointChanged");
1816 virtual void cleared()
1818 callDelegateMethod("cleared");
1822 void callDelegateMethod(const char* method)
1825 naMember_cget(_nasal->context(), _instance, method, &f);
1827 return; // no method on the delegate
1831 arg[0] = ghostForFlightPlan(_nasal->context(), _plan);
1832 _nasal->callMethod(f, _instance, 1, arg, naNil());
1841 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1844 NasalFPDelegateFactory(naRef code)
1846 _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1848 _gcSaveKey = _nasal->gcSave(_func);
1851 ~NasalFPDelegateFactory()
1853 _nasal->gcRelease(_gcSaveKey);
1856 virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1859 args[0] = ghostForFlightPlan(_nasal->context(), fp);
1860 naRef instance = _nasal->call(_func, 1, args, naNil());
1861 if (naIsNil(instance)) {
1865 return new NasalFPDelegate(fp, _nasal, instance);
1873 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1875 if ((argc < 1) || !naIsFunc(args[0])) {
1876 naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1879 NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1880 FlightPlan::registerDelegateFactory(factory);
1885 static WayptRef wayptFromArg(naRef arg)
1887 WayptRef r = wayptGhost(arg);
1892 FGPositioned* pos = positionedGhost(arg);
1894 // let's check if the arg is hash, coudl extra a geod and hence build
1895 // a simple waypoint
1900 // special-case for runways
1901 if (pos->type() == FGPositioned::RUNWAY) {
1902 return new RunwayWaypt((FGRunway*) pos, NULL);
1905 return new NavaidWaypoint(pos, NULL);
1908 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1910 naRef result = naNewVector(c);
1911 BOOST_FOREACH(WayptRef wpt, wps) {
1912 naVec_append(result, ghostForWaypt(c, wpt.get()));
1917 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1920 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1923 WayptRef start = wayptFromArg(args[0]),
1924 end = wayptFromArg(args[1]);
1926 if (!start || !end) {
1927 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1931 bool highLevel = true;
1932 if ((argc > 2) && naIsString(args[2])) {
1933 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1940 Airway::highLevel()->route(start, end, route);
1942 Airway::lowLevel()->route(start, end, route);
1945 return convertWayptVecToNasal(c, route);
1948 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1951 int argOffset = geodFromArgs(args, 0, argc, pos);
1953 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1954 naRuntimeError(c, "createWP: no identifier supplied");
1957 string ident = naStr_data(args[argOffset++]);
1958 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1960 // set waypt flags - approach, departure, pseudo, etc
1961 if (argc > argOffset) {
1962 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1966 return ghostForWaypt(c, wpt);
1969 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1972 naRuntimeError(c, "createWPFrom: need at least one argument");
1975 FGPositioned* positioned = positionedGhost(args[0]);
1977 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1981 if (positioned->type() == FGPositioned::RUNWAY) {
1982 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1984 wpt = new NavaidWaypoint(positioned, NULL);
1987 // set waypt flags - approach, departure, pseudo, etc
1989 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1993 return ghostForWaypt(c, wpt);
1996 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1998 FlightPlan* fp = flightplanGhost(me);
2000 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
2005 index = fp->currentIndex();
2007 index = (int) naNumValue(args[0]).num;
2010 if ((index < 0) || (index >= fp->numLegs())) {
2014 return ghostForLeg(c, fp->legAtIndex(index));
2017 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
2019 FlightPlan* fp = flightplanGhost(me);
2021 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
2023 return ghostForLeg(c, fp->currentLeg());
2026 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
2028 FlightPlan* fp = flightplanGhost(me);
2030 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
2032 return ghostForLeg(c, fp->nextLeg());
2035 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
2037 FlightPlan* fp = flightplanGhost(me);
2039 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
2041 return naNum(fp->numLegs());
2044 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2046 FlightPlan* fp = flightplanGhost(me);
2048 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2051 WayptRef wp = wayptGhost(args[0]);
2052 int index = fp->numLegs();
2053 fp->insertWayptAtIndex(wp.get(), index);
2054 return naNum(index);
2057 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2059 FlightPlan* fp = flightplanGhost(me);
2061 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2064 WayptRef wp = wayptGhost(args[0]);
2065 int index = -1; // append
2066 if ((argc > 1) && naIsNum(args[1])) {
2067 index = (int) args[1].num;
2070 fp->insertWayptAtIndex(wp.get(), index);
2074 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2076 FlightPlan* fp = flightplanGhost(me);
2078 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2081 WayptRef wp = wayptGhost(args[0]);
2082 int index = -1; // append
2083 if ((argc > 1) && naIsNum(args[1])) {
2084 index = (int) args[1].num;
2087 fp->insertWayptAtIndex(wp.get(), index + 1);
2091 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2093 FlightPlan* fp = flightplanGhost(me);
2095 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2099 if (!naIsVector(args[0])) {
2100 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2103 int count = naVec_size(args[0]);
2104 for (int i=0; i<count; ++i) {
2105 Waypt* wp = wayptGhost(naVec_get(args[0], i));
2111 int index = -1; // append
2112 if ((argc > 1) && naIsNum(args[1])) {
2113 index = (int) args[1].num;
2116 fp->insertWayptsAtIndex(wps, index);
2120 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2122 FlightPlan* fp = flightplanGhost(me);
2124 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2127 if ((argc < 1) || !naIsNum(args[0])) {
2128 naRuntimeError(c, "bad argument to flightplan.deleteWP");
2131 int index = (int) args[0].num;
2132 fp->deleteIndex(index);
2136 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2138 FlightPlan* fp = flightplanGhost(me);
2140 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2147 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2149 FlightPlan* fp = flightplanGhost(me);
2151 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2155 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2158 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2159 fp->clearWayptsWithFlag(flag);
2163 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2165 FlightPlan* fp = flightplanGhost(me);
2167 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2170 return ghostForFlightPlan(c, fp->clone());
2173 static naRef f_flightplan_pathGeod(naContext c, naRef me, int argc, naRef* args)
2175 FlightPlan* fp = flightplanGhost(me);
2177 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2180 if ((argc < 1) || !naIsNum(args[0])) {
2181 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2184 if ((argc > 1) && !naIsNum(args[1])) {
2185 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2188 int index = (int) args[0].num;
2189 double offset = (argc > 1) ? args[1].num : 0.0;
2190 naRef result = naNewHash(c);
2191 SGGeod g = fp->pointAlongRoute(index, offset);
2192 hashset(c, result, "lat", naNum(g.getLatitudeDeg()));
2193 hashset(c, result, "lon", naNum(g.getLongitudeDeg()));
2198 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2200 FlightPlan::Leg* leg = fpLegGhost(me);
2202 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2206 naRuntimeError(c, "bad arguments to leg.setSpeed");
2209 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2210 leg->setSpeed(rr, args[0].num);
2214 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2216 FlightPlan::Leg* leg = fpLegGhost(me);
2218 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2222 naRuntimeError(c, "bad arguments to leg.setAltitude");
2225 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2226 leg->setAltitude(rr, args[0].num);
2230 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2232 FlightPlan::Leg* leg = fpLegGhost(me);
2234 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2237 RoutePath path(leg->owner());
2238 SGGeodVec gv(path.pathForIndex(leg->index()));
2240 naRef result = naNewVector(c);
2241 BOOST_FOREACH(SGGeod p, gv) {
2242 // construct a geo.Coord!
2243 naRef coord = naNewHash(c);
2244 hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2245 hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2246 naVec_append(result, coord);
2252 static naRef f_leg_courseAndDistanceFrom(naContext c, naRef me, int argc, naRef* args)
2254 FlightPlan::Leg* leg = fpLegGhost(me);
2256 naRuntimeError(c, "leg.courseAndDistanceFrom called on non-flightplan-leg object");
2260 geodFromArgs(args, 0, argc, pos);
2264 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(pos);
2266 naRef result = naNewVector(c);
2267 naVec_append(result, naNum(courseDeg));
2268 naVec_append(result, naNum(distanceM * SG_METER_TO_NM));
2272 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2274 flightgear::Waypt* w = wayptGhost(me);
2276 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2279 FGPositioned* pos = w->source();
2284 switch (pos->type()) {
2285 case FGPositioned::VOR:
2286 case FGPositioned::NDB:
2287 case FGPositioned::ILS:
2288 case FGPositioned::LOC:
2289 case FGPositioned::GS:
2290 case FGPositioned::DME:
2291 case FGPositioned::TACAN: {
2292 FGNavRecord* nav = (FGNavRecord*) pos;
2293 return ghostForNavaid(c, nav);
2301 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2303 flightgear::Waypt* w = wayptGhost(me);
2305 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2308 FGPositioned* pos = w->source();
2309 if (!pos || FGAirport::isAirportType(pos)) {
2313 return ghostForAirport(c, (FGAirport*) pos);
2316 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2318 flightgear::Waypt* w = wayptGhost(me);
2320 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2323 FGPositioned* pos = w->source();
2324 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2328 return ghostForRunway(c, (FGRunway*) pos);
2331 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2333 Procedure* proc = procedureGhost(me);
2335 naRuntimeError(c, "procedure.transition called on non-procedure object");
2338 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2339 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2342 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2343 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2345 return ghostForProcedure(c, trans);
2348 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2350 Procedure* proc = procedureGhost(me);
2352 naRuntimeError(c, "procedure.route called on non-procedure object");
2355 // wrapping up tow different routines here - approach routing from the IAF
2356 // to the associated runway, and SID/STAR routing via an enroute transition
2357 // and possibly a runway transition or not.
2358 if (Approach::isApproach(proc->type())) {
2361 iaf = wayptFromArg(args[0]);
2365 Approach* app = (Approach*) proc;
2366 if (!app->route(iaf, r)) {
2367 SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2371 return convertWayptVecToNasal(c, r);
2372 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2373 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2377 FGRunway* rwy = runwayGhost(args[0]);
2378 if (rwy) ++argOffset;
2380 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2381 Transition* trans = NULL;
2382 if (argOffset < argc) {
2383 trans = (Transition*) procedureGhost(args[argOffset]);
2386 // note either runway or trans may be NULL - that's ok
2388 if (!ad->route(rwy, trans, r)) {
2389 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2393 return convertWayptVecToNasal(c, r);
2397 // Table of extension functions. Terminate with zeros.
2398 static struct { const char* name; naCFunction func; } funcs[] = {
2399 { "carttogeod", f_carttogeod },
2400 { "geodtocart", f_geodtocart },
2401 { "geodinfo", f_geodinfo },
2402 { "airportinfo", f_airportinfo },
2403 { "findAirportsWithinRange", f_findAirportsWithinRange },
2404 { "findAirportsByICAO", f_findAirportsByICAO },
2405 { "navinfo", f_navinfo },
2406 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2407 { "findNavaidByFrequency", f_findNavaidByFrequency },
2408 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2409 { "findNavaidsByID", f_findNavaidsByIdent },
2410 { "findFixesByID", f_findFixesByIdent },
2411 { "flightplan", f_route },
2412 { "registerFlightPlanDelegate", f_registerFPDelegate },
2413 { "createWP", f_createWP },
2414 { "createWPFrom", f_createWPFrom },
2415 { "airwaysRoute", f_airwaySearch },
2416 { "magvar", f_magvar },
2417 { "courseAndDistance", f_courseAndDistance },
2418 { "greatCircleMove", f_greatCircleMove },
2419 { "tileIndex", f_tileIndex },
2420 { "tilePath", f_tilePath },
2425 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2427 airportPrototype = naNewHash(c);
2428 hashset(c, gcSave, "airportProto", airportPrototype);
2430 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2431 hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
2432 hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2433 hashset(c, airportPrototype, "taxiway", naNewFunc(c, naNewCCode(c, f_airport_taxiway)));
2434 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2435 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2436 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2437 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2438 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2439 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2440 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2441 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2442 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2443 hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2445 flightplanPrototype = naNewHash(c);
2446 hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2448 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2449 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2450 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2451 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2452 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2453 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2454 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2455 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2456 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2457 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2458 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2459 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2460 hashset(c, flightplanPrototype, "pathGeod", naNewFunc(c, naNewCCode(c, f_flightplan_pathGeod)));
2462 waypointPrototype = naNewHash(c);
2463 hashset(c, gcSave, "wayptProto", waypointPrototype);
2465 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2466 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2467 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2469 procedurePrototype = naNewHash(c);
2470 hashset(c, gcSave, "procedureProto", procedurePrototype);
2471 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2472 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2474 fpLegPrototype = naNewHash(c);
2475 hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2476 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2477 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2478 hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2479 hashset(c, fpLegPrototype, "courseAndDistanceFrom", naNewFunc(c, naNewCCode(c, f_leg_courseAndDistanceFrom)));
2481 for(int i=0; funcs[i].name; i++) {
2482 hashset(c, globals, funcs[i].name,
2483 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2489 void postinitNasalPositioned(naRef globals, naContext c)
2491 naRef geoModule = naHash_cget(globals, (char*) "geo");
2492 if (naIsNil(geoModule)) {
2493 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2497 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");